Javascript jQuery 每个表行中的循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10431987/
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
jQuery each loop in table row
提问by ANP
I am having something like:
我有这样的事情:
<table id="tblOne">
<tbody>
<tr>
<td>
<table id="tblTwo">
<tbody>
<tr>
<td>
Items
</td>
</tr>
<tr>
<td>
Prod
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td>
Item 1
</td>
</tr>
<tr>
<td>
Item 2
</td>
</tr>
</tbody>
</table>
I have written jQuery to loop through each tr like:
我已经编写了 jQuery 来循环遍历每个 tr,例如:
$('#tblOne tr').each(function() {...code...});
But problem is that it loops through the "tr" of "tblTwo" also which I don't want. Can anyone please suggest something to solve this?
但问题是它也循环了我不想要的“tblTwo”的“tr”。任何人都可以提出一些建议来解决这个问题吗?
回答by Fabrizio Calderan
In jQuery just use:
在 jQuery 中只需使用:
$('#tblOne > tbody > tr').each(function() {...code...});
Using the children selector (>
) you will walk over all the children (and not alldescendents), example with three rows:
使用子选择器 ( >
) 您将遍历所有子项(而不是所有后代),例如三行:
$('table > tbody > tr').each(function(index, tr) {
console.log(index);
console.log(tr);
});
Result:
结果:
0
<tr>
1
<tr>
2
<tr>
In VanillaJSyou can use document.querySelectorAll()
and walk over the rows using forEach()
在VanillaJS 中,您可以使用document.querySelectorAll()
并遍历行forEach()
[].forEach.call(document.querySelectorAll('#tblOne > tbody > tr'), function(index, tr) {
/* console.log(index); */
/* console.log(tr); */
});
回答by GNi33
Just a recommendation:
只是一个建议:
I'd recommend using the DOM table implementation, it's very straight forward and easy to use, you really don't need jQuery for this task.
我建议使用 DOM 表实现,它非常直接且易于使用,您真的不需要 jQuery 来完成这项任务。
var table = document.getElementById('tblOne');
var rowLength = table.rows.length;
for(var i=0; i<rowLength; i+=1){
var row = table.rows[i];
//your code goes here, looping over every row.
//cells are accessed as easy
var cellLength = row.cells.length;
for(var y=0; y<cellLength; y+=1){
var cell = row.cells[y];
//do something with every cell here
}
}
回答by Sarfraz
Use immediate children selector>
:
使用直接子选择器>
:
$('#tblOne > tbody > tr')
Description: Selects all direct child elementsspecified by "child" of elements specified by "parent".
描述:选择由“parent”指定的元素的“child”指定的所有直接子元素。