Javascript 未捕获的类型错误:对象 #<HTMLDivElement> 没有方法“attr”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13533089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:18:29  来源:igfitidea点击:

Uncaught TypeError: Object #<HTMLDivElement> has no method 'attr'

javascriptjquery

提问by Gleiemeister 2000

Im trying to grab my divs with the class tooltip.

我试图用类工具提示来获取我的 div。

And then do something like this:

然后做这样的事情:

var schemes = $(".tooltip");

for (var i in schemes) {
    var scheme = schemes[i];
    console.log(scheme.attr("cost"));
}

But it throws the above error. What am i missing? (Im new to javascript + jquery obviously)

但它会引发上述错误。我错过了什么?(我显然是 javascript + jquery 的新手)

回答by VisioN

If you use for-loopto iterate jQuery set, you should get the elements with eq()method, but not using square bracket notation (i.e. []). The code like $(".tooltip")[i]will pick up DOM elements, but notjQuery objects.

如果您使用for-loop迭代 jQuery 集,您应该使用eq()方法获取元素,但不要使用方括号表示法(即[])。类似的代码$(".tooltip")[i]会选择 DOM 元素,但不会选择jQuery 对象。

var schemes = $(".tooltip");
for (var i = 0; i < schemes.length; i++) {
    var scheme = schemes.eq(i);
    console.log(scheme.attr("cost"));
}

However, you may always use each()to iterate jQuery set:

但是,您可能总是使用each()迭代 jQuery 集:

$(".tooltip").each(function() {
    var scheme = $(this);
    console.log(scheme.attr("cost"));
});

回答by adeneo

var schemes = $(".tooltip");

schemes.each(function(index, elem) {
    console.log($(elem).attr('cost'));
});

As a sidenote "cost" is not a valid attribute for any element as far as I know, and you should probably be using data attributes.

作为旁注,据我所知,“成本”不是任何元素的有效属性,您可能应该使用数据属性。