通过HTML表迭代返回Uncaught TypeError:'0'属性为undefined

时间:2015-05-06 12:56:23

标签: javascript jquery

我编写了一个循环遍历HTML表格中每个单元格的函数,并在匹配文本模式时'red.png'将jQuery方法应用于页面上的另一个元素。

然而,当执行所述功能时,我收到了

  

“未捕获的TypeError:无法读取未定义的属性'0'”

我原本以为这可能是因为在页面执行时没有在DOM中声明表,但是通过在console.log中输出下面的“table”变量来测试它 - 我可以看到表格很好。

我的代码如下:

function poll() {
    var table = document.getElementById("myTable");
    //console.log(table);
    for (var i = 0, cell; table.cells[i]; i++) {
        if (cell[i].indexOf('red.png') != -1) {
            $("#tenantPreviewLive").css('background-color', '#FF0000');
            $("#maximiseLive").css('background-color', '#FF0000');
        }
    }
}

感谢所有回复!

1 个答案:

答案 0 :(得分:4)

您永远不会在循环中设置cell。您可能打算在条件(中间位)中执行此操作。另外,您正在尝试在元素上使用indexOf;你可能想要使用它的HTML:

function poll() {
    var table = document.getElementById("myTable");
    //console.log(table);
    for (var i = 0; cell = table.cells[i]; i++) {
    //              ^^^^^^^
        if (cell.innerHTML.indexOf('red.png') != -1) {
    //      ^^^^^^^^^^^^^^
            $("#tenantPreviewLive").css('background-color', '#FF0000');
            $("#maximiseLive").css('background-color', '#FF0000');
        }
    }
}

我不建议使用该格式的循环,但这是最小的变化。

虽然it doesn't look to me like table elements have a cells property。他们有rows,而后者cells。这意味着两个循环(table.rows之一和每行cells上的另一个循环。

但是当您使用jQuery时,可以使用each

function poll() {
    $("#myTable td").each(function() {
        if (this.innerHTML.indexOf('red.png') != -1) {
            $("#tenantPreviewLive").css('background-color', '#FF0000');
            $("#maximiseLive").css('background-color', '#FF0000');
        }
    });
}

(假设您的#myTable中没有任何表格。)

您可能还想停止发现第一个:

function poll() {
    $("#myTable td").each(function() {
        if (this.innerHTML.indexOf('red.png') != -1) {
            $("#tenantPreviewLive").css('background-color', '#FF0000');
            $("#maximiseLive").css('background-color', '#FF0000');
            return false; // <==== Stops the `each` loop
        }
    });
}

甚至可能使用jQuery&#39; :contains伪选择器:

function poll() {
    if ($("#myTable td:contains(red.png)").length > 0) {
        $("#tenantPreviewLive").css('background-color', '#FF0000');
        $("#maximiseLive").css('background-color', '#FF0000');
    }
}