更改innerHTML函数的Javascript不起作用



我正在构建一个由表中的9个单元格组成的接口。当一个人将鼠标悬停在一个单元格上时,我希望其他单元格变得可见,并更改其中一些单元格的文本内容。如果我创建单独的函数来更改每个单元格的内容,我可以很好地做到这一点,但这太疯狂了。

我想要一个单独的函数来根据所涉及的单元格更改文本。我创建了一个可以接受n个参数的函数,并根据传递给该函数的参数进行循环更改。它不起作用。

函数的代码如下。如果我调用它onMouseOver="changebox('div3')",当我将鼠标悬停在单元格上时,该参数会变成函数。如果我取消注释document.write(cell)语句,在本例中,它会将div3打印到屏幕上。那么…为什么它不对div3单元格的内容进行任何更改?

function changebox() {
    for (var i = 0; i < arguments.length; i++) {
        var cell = document.getElementById(arguments[i]).id;
        var text = "";
        if (cell == 'div3') {
            text = "Reduced Travel";
        } else if (cell == 'div4') {
            text = "Reduced Cost";
        }
        //document.write(cell)
        cell.innerHTML = text;
    }
}

在代码中,cell是一个字符串,用于保存对象的id。按照以下更新代码

function changebox() {
    for (var i = 0; i < arguments.length; i++) {
        var cell = document.getElementById(arguments[i]),
            text = "";
        if (cell.id == 'div3') {
            text = "Reduced Travel";
        } else if (cell.id == 'div4') {
            text = "Reduced Cost";
        }
        //document.write(cell)
        cell.innerHTML = text;
    }
}

更新:你可以按照@Tushar的建议减少代码。

无需在arguments上迭代(假设只有两个元素,但可以针对更多元素进行修改)。

function changebox() {
    // As arguments is not real array, need to use call
    // Check if div is present in the arguments array
    var div3Index = [].indexOf.call(arguments, 'div3') > -1,
        div4Index = [].indexOf.call(arguments, 'div4') > -1;
    // If present then update the innerHTML of it accordingly        
    if (div3Index) {
        document.getElementById('div3').innerHTML = 'Reduced Travel';
    } else if (div4Index) {
        document.getElementById('div4').innerHTML = 'Reduced Cost';
    }
}
function changebox() {
    var args = [].slice.call(arguments);
    args.map(document.getElementById.bind(document)).forEach(setElement);
}
function setElement(ele) {
  if (ele.id === 'div3') {
     ele.innerHTML = "Reduced Travel";
  } else if (ele.id === 'div4') {
     ele.innerHTML = "Reduced Cost";
  }
}

这使您的功能易于测试

当您为单元格变量分配元素的id并更改无效单元格的innerHTML时。

    var changeText = function() {
    console.log("in change text");
    for(var i= 0; i<arguments.length; i++) {
        var elem = document.getElementById(arguments[i]);
        var cell = document.getElementById(arguments[i]).id;
        var text = "";
        console.log(cell)
        if (cell === "div-1") {
            text = cell+" was selected!!";
        } else if(cell === "div-3") {
            text = cell+" was selected!!";
        } else {
            text = cell+" was selected";
        }
        elem.innerHTML = text;
    }
}

这将正确地更改div mouseovered的文本!!

最新更新