javascript:循环遍历表中的所有单元格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14591538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript: looping through all cells in table
提问by dot
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;
}
}
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.
当我测试这段代码时,警报(表格)代码正在工作 - 它返回“对象 HTMLTableElement”,表格长度的警报返回 4,这也是正确的。但是循环中的警报语句永远不会发生。你能告诉我循环控制哪里出了问题吗?谢谢。
回答by Niet the Dark Absol
table
contains rows[]
, which themselves contain cells[]
. You can't get the cells[]
directly from the table
.
table
包含rows[]
,其本身包含cells[]
。你不能cells[]
直接从table
.
You could use table.getElementsByTagName('td')
as a shortcut, provided there are no nested tables.
如果table.getElementsByTagName('td')
没有嵌套表,您可以用作快捷方式。
Otherwise, you should loop through each of the rows[]
and in that loop you can loop through the cells[]
.
否则,您应该遍历每个rows[]
并且在该循环中您可以遍历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.
}
}
回答by sdespont
Try like this :
像这样尝试:
var $table = $('#assignedvlans tbody td');
$.map($table,function(){
if ($(this).text() == IdforVlanToAdd)
{
alert('This vlan is already associated with the port.');
return;
}
});
回答by Shubham Bhardwaj
var myDataArr = [];
$('#dynamic_cards tr').each(function(){
$(this).find('td').each(function(){
myDataArr.push($(this).text());
});
});
console.log(myDataArr);
回答by Jonathan M
The reason you're not getting anyalerts inside the loop is your for
loop is not structured correctly. It quits immediately because the assignment cell = table.cells[i]
returns false.
您没有在循环内收到任何警报的原因是您的for
循环结构不正确。它立即退出,因为赋值cell = table.cells[i]
返回 false。