[英]How to get every id on a row in a table with jQuery?
為什么在每次迭代中都給出第一個ID? 或更妙的是,如何獲得每個ID?
$('#foo').on('click', function () {
var rows = $('#mytable tbody tr.selected');
for (var i = 0; rows[i]; i++) {
console.log('rows.attr("id")' + rows.attr('id'));
}
});
當選擇2行時,此打印兩次“ 17”。 我可以看到第二行是“ 18”,所以出了點問題。
我建議您使用.each()
回調是在當前DOM元素的上下文中觸發的,因此關鍵字
this
引用了該元素。
var rows = $('#mytable tbody tr.selected');
rows.each(function(){
console.log(this.id); //Here this refers current row
})
要么
var rows = $('#mytable tbody tr.selected');
//Here you need to add break condition
for (var i = 0; i < rows.length; i++) {
console.log('rows.attr("id")' + rows[i].id); //access row using index
}
您可以使用jquery映射並獲取數組中的值:
$('#foo').on('click', function() { var rows = $('#mytable tbody tr.selected'); var ids = rows.map(function() { return this.id; }).get(); console.log(ids);//outputs ['row1', 'row2', 'row3'] });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="mytable"> <tr id="row1" class="selected"> <td></td> </tr> <tr id="row2" class="selected"> <td></td> </tr> <tr id="row3" class="selected"> <td></td> </tr> </table> <input type="button" id="foo" value="Get all row id" />
參考文獻:
希望這項工作!
$('#foo').on('click', function () {
var rows = $('#mytable tbody tr.selected');
for (var i = 0; rows.length; i++) {
console.log('rows.attr("id")' + rows[i].id);
}
});
給定選擇器(此處為#mytable tbody tr.selected
)的jQuery實例可以在執行時立即引用。 但是,這具有有趣的效果,即返回內部指針當前引用的集合中的元素(在大多數情況下,這被視為第一個元素。請參見此處 。)。
為了避免這種情況,請考慮如下修改代碼:
使用jQuery對象作為數組:
$('#foo').on('click', function () { var rows = $('#mytable tbody tr.selected'); for (var i = 0; i<rows.length; i++) { console.log('rows.attr("id")' + rows[i].attr('id')); } });
使用jQuery.forEach
進行迭代:
$('#foo').on('click', function () { var rows = $('#mytable tbody tr.selected'); rows.forEach(function() { console.log($(this).attr("id")); }); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.