javascript:循环遍历表中的所有单元格
我试图循环遍历表中的所有单元格并对值进行比较。
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,这也是正确的。 但循环内的警报语句永远不会发生。 你能告诉我循环控制在哪里出错吗? 谢谢。
table
包含rows[]
,它们本身包含cells[]
。 你不能直接从table
获取cells[]
。
如果没有嵌套表,可以使用table.getElementsByTagName('td')
作为快捷方式。
否则,你应该循环遍历每一rows[]
并在该循环中循环遍历cells[]
。
var table = document.getElementById('assignedvlans'), rows = table.rows, rowcount = rows.length, r, cells, cellcount, c, cell; for( r=0; r
试试这样:
var $table = $('#assignedvlans tbody td'); $.map($table,function(){ if ($(this).text() == IdforVlanToAdd) { alert('This vlan is already associated with the port.'); return; } });
你在循环中没有得到任何警报的原因是你的for
循环结构不正确。 它立即退出,因为赋值cell = table.cells[i]
返回false。
var myDataArr = []; $('#dynamic_cards tr').each(function(){ $(this).find('td').each(function(){ myDataArr.push($(this).text()); }); }); console.log(myDataArr);