javascript:循环遍历表中的所有单元格 [英] javascript: looping through all cells in table

查看:70
本文介绍了javascript:循环遍历表中的所有单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遍历表中的所有单元格并对值进行比较。

i'm trying to loop through all the cells in a table and do a comparison on the value.

            var table = document.getElementById("assignedvlans");
            alert(table);
            alert($('#assignedvlans tbody tr').length);
            for (var i = 0, cell; cell = table.cells[i]; i++) {
                 //iterate through all cells in table.
                 alert('in the loop');
                 alert(cell.val());
                 if (cell.val == IdforVlanToAdd)
                 {
                    alert('This vlan is already associated with the port.');
                    $bexit = true;
                    break;
                 }                  
            }

当我测试此代码时,警报(表格)代码正在运行 - 它返回对象HTMLTableElement,表长度的警报返回4,这也是正确的。
但循环内的警报语句永远不会发生。
你能告诉我循环控制出了什么问题吗?
谢谢。

When i test this code, the alert(table) code is working - it returns "object HTMLTableElement" and the alert for the table lengths returns 4, which is also correct. But the alert statements inside the loop never happen. Can you tell me where i'm going wrong with the loop control? Thanks.

推荐答案

table 包含 rows [] ,它们本身包含 cells [] 。你不能直接从获得 cells []

table contains rows[], which themselves contain cells[]. You can't get the cells[] directly from the table.

如果没有嵌套表,你可以使用 table.getElementsByTagName('td')作为快捷方式。

You could use table.getElementsByTagName('td') as a shortcut, provided there are no nested tables.

否则,你应该循环遍历每个 rows [] ,然后在那个循环中你可以遍历 cells []

Otherwise, you should loop through each of the rows[] and in that loop you can loop through the cells[].

var table = document.getElementById('assignedvlans'),
    rows = table.rows, rowcount = rows.length, r,
    cells, cellcount, c, cell;
for( r=0; r<rowcount; r++) {
    cells = rows[r].cells;
    cellcount = cells.length;
    for( c=0; c<cellcount; c++) {
        cell = cells[c];
        // now do something.
    }
}

这篇关于javascript:循环遍历表中的所有单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆