3 回答

TA貢獻1775條經驗 獲得超8個贊
您可以一次全部使用選擇器來選擇所有元素。考慮以下代碼。
$(function() {
$("#foo tr").each(function(i, el) {
$(el).attr("id", "row-" + (i + 1));
console.log($(el).html().trim());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="foo">
<tr>
<td>Item 1</td>
</tr>
<tr>
<td>Item 2</td>
</tr>
<tr>
<td>Item 3</td>
</tr>
</table>
使用 CSS 選擇器,您可以選擇<tr>元素中具有 id 的所有元素foo。

TA貢獻1757條經驗 獲得超7個贊
正如其他人指出的那樣,<tr>元素不應該是元素的子<div>元素。
也就是說,您只需要按元素類型獲取孩子- 即
$(".foo").children("tr");
請注意,您<div>的class“foo”不是id“foo”!
如果您想在 id 上進行選擇,那么您的 HTML 應該更像這樣。
<table id="foo">
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
</table>
那么你的選擇將是...
$("#foo").children("tr");

TA貢獻1796條經驗 獲得超10個贊
試試這個,如果你要去div:
<div class="foo">
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
</div>
var rows = $(".foo").find('tr');
$.each( rows , function( i, l ){
console.log( "Index #" + i + ": " + l );
});
這將為您的 div 下的所有 'tr' 提供類 'foo' 。
但就像其他人說的,先修復html。使用如下table標簽:
<table id="foo">
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
</table>
var rows = $("#foo").find('tr');
$.each( rows , function( i, l ){
console.log( "Index #" + i + ": " + l );
});
添加回答
舉報