JQuery 表行中的每个循环

我现在有这样的感觉:

<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>

我已经编写了 jQuery 来遍历每个 tr:

$('#tblOne tr').each(function() {...code...});

但问题是,它循环通过“ tblTwo”的“ tr”,这也是我不想要的。 有人能提出解决办法吗?

462800 次浏览

In jQuery just use:

$('#tblOne > tbody  > tr').each(function() {...code...});

Using the children selector (>) you will walk over all the children (and not all descendents), 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 VanillaJS you can use document.querySelectorAll() and walk over the rows using forEach()

[].forEach.call(document.querySelectorAll('#tblOne > tbody  > tr'), function(index, tr) {
/* console.log(index); */
/* console.log(tr); */
});

Use immediate children selector >:

$('#tblOne > tbody  > tr')

Description: Selects all direct child elements specified by "child" of elements specified by "parent".

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.

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
}
}