'undefined' 从 tr 上的 .each 运行 返回,选择了 id

'undefined' returned from .each ran on tr with id selection

问题

我正在尝试 运行 遍历具有特定格式 ID 的 table 中的每一行。 selected 的行数正确,但每当我尝试从 obj 获取属性时,我都会遇到 'undefined' 问题。

<tr class="" data-uid="45" id="fixed_user_45">...

还有 javascript...

$('tr[id^="fixed_user_"] ').each(function(obj, i) {

var id = $(obj).id; // returns 'undefined'
console.log(id); //prints 'undefined' the correct number of times

});

无论我尝试 select 的属性如何,以及我如何处理它 - 即 innerText、innerHTML、.attr('data-uid'),都会发生这种情况。都是未定义的。


其他详情:

为了完整性...我将在每个 td 之后循环,所以在上面的每个函数中嵌套了以下内容。

$('td').each(function (obj, i) {


感谢大家的帮助。

obj 是索引,i 是您案例的元素。要获得 data-uid 使用 data() 函数,如下所示。

$('tr[id^="fixed_user_"] ').each(function (obj, i) {
     var id = $(i).data('uid'); 
     console.log(id); 
});

每个方法:

$(array/object).each(function(index,object){});

代码:

$('tr[id^="fixed_user_"] ').each(function(i, obj) {

var id = obj.id; // returns 'undefined'
console.log(id); //prints 'undefined' the correct number of times

});

注意JQueryeach方法:

.each( function )
function Type: Function( Integer index, Element element ) A function to execute for each matched element.

$('tr[id^="fixed_user_"]').each(function(index, obj) {

    var id = $(obj).data('uid);

});

可以使用下面的代码得到需要的结果。

$('tr[id^="fixed_user_"] ').each(function() {

  console.log($(this).attr('id'));  //return each id
  console.log($(this).attr('data-uid'));// returns 'data-uid'
  console.log($(this).data('uid'));// also returns 'data-uid'

});

在 javascript 片段中,您的参数顺序错误

.each(function(obj, i) {

正确的顺序是

.each(function(i, obj) {

然后你必须调用jQuery .attr()函数来获取id。

$(obj).attr('id')

但是你可以不获取任何参数(如果你不需要索引)并使用 this 作为当前对象。

$(this).attr('id');

要查看它是否正常工作,请访问此 jsfiddle https://jsfiddle.net/zv6guhzn/1/ 如果你想循环嵌套 td,我建议使用 .find(),它比一般选择器 $() 更快,因为它从选定的开始搜索嵌套元素。

$(obj).find('td').each(itd, objtd){
    console.log( $(objtd).text() );
}

带有嵌套循环的完整示例 https://jsfiddle.net/zv6guhzn/2/

来源https://api.jquery.com/each/#example-2