在搜索特定元素时如何获取直接子元素?例如,我想获取表 t1
的 tr
元素。
<table id="t1" bgcolor="yellow">
<tbody>
<tr>
<td>This is Cell 1</td>
<td>This is Cell 2</td>
</tr>
<tr>
<td>This is Cell 3</td>
<td>
<table id="t2" bgcolor="red">
<tbody>
<tr>
<td>This is Cell 1</td>
<td>This is Cell 2</td>
</tr>
<tr>
<td>This is Cell 3</td>
<td>This is Cell 4</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
我试过这个:
'Count = ' + $('#t1 tbody').children('tr').length;
但是,我的计数是 4,我不明白为什么?
Here是一个完整的例子:
最佳答案
使用:
'Count = ' + $('#t1 > tbody').children('tr').length;
// or: $("#t1 > tbody > tr").length
// or: $("#t1")[0].rows.length; // In this case, equal to previous code.
// Warning: This also includes the rows from
// the <thead> and <tfoot> sections.
您当前的代码显示 4,因为您有两个 <tbody>
表中的元素 #t1
:
<table id="t1" bgcolor="yellow"> <-- #t1
<tbody> <--- tbody
<tr> ... </tr> <----- Child 1
<tr> ... <----- Child 2
<tbody> <--- tbody (unexpected?)
<tr> ... </tr> <----- Child 3
<tr> ... </tr> <----- Child 4
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
关于javascript - 使用 jQuery 查找直系子节点,不再继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9385363/