javascript 对象 [object HTMLAnchorElement] 没有方法 'attr'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16073677/
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-10-27 03:10:52  来源:igfitidea点击:

Object [object HTMLAnchorElement] has no method 'attr'

javascriptjqueryhtmldom

提问by Solorzano Jose

I'm examining a DOM element using console.log. The DOM element is an anchor:

我正在使用 console.log 检查 DOM 元素。DOM 元素是一个锚点:

 <a href="#" class="videoimage" data-id="ks3H_s3e-Wc"></a>

When I try to access its id and output it using either of the following lines:

当我尝试访问其 id 并使用以下任一行输出时:

console.log($this.attr(data-id));

or

或者

console.log($this.data('id'));

I get an error:

我收到一个错误:

Object [object HTMLAnchorElement] has no method 'attr'

对象 [object HTMLAnchorElement] 没有方法 'attr'

('data' in the second case)

(第二种情况下的“数据”)

Does an anchor element not have the attr or data methods, or is my mistake something else?

锚元素是否没有 attr 或 data 方法,或者我的错误是什么?

回答by Coin_op

That looks like its because your thisreference is not a jqueryobject. Try these instead:

这看起来像它,因为您的this引用不是jquery对象。试试这些:

$(this).data('id')
$(this).attr('data-id')

回答by Hanlet Esca?o

It is telling you exactly what the problem is. .dataand .attrare jQuery functions. If your want to get an attribute value using a javascript object do the following, after giving an id to your element:

它准确地告诉你问题是什么。.data.attr是 jQuery 函数。如果您想使用 javascript 对象获取属性值,请在为元素提供 id 后执行以下操作:

console.log(document.getElementById("a").getAttribute("data-id"));

jsFiddle: http://jsfiddle.net/hescano/pFdEj/

jsFiddlehttp: //jsfiddle.net/hescano/pFdEj/

回答by Charlie

Something else is wrong in your page, then. The following doeswork:

那么,您的页面中还有其他问题。以下确实有效:

$(this).data("id")

http://jsfiddle.net/RQw8E/

http://jsfiddle.net/RQw8E/

How are you using $(this)?

你怎么用$(this)

回答by SomeShinyObject

Works for me:

对我有用:

HTML

HTML

<a href="#" class="videoimage" data-id="ks3H_s3e-Wc">Click</a>

JavaScript

JavaScript

$(".videoimage").click(function() {
    var dataID = $(this).data("id");
    var dataIDAttr = $(this).attr("data-id");
    console.log(dataID);
    console.log(dataIDAttr);
});

JSFiddle

JSFiddle

Are you sure you attached some sort of event to the function that calls these statements?

您确定将某种事件附加到调用这些语句的函数中吗?

You could also use vanilla JS

你也可以使用 vanilla JS

var anchorArr = document.getElementsByTagName("a");
for (var i = 0; i < anchorArr.length; i++) {
    if(anchorArr[i].getAttribute("class")==="videoimage") {
        //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
        //quick and dirty, there are better ways to do this
        console.log(anchorArr[i].getAttribute("data-id"));
    }
}

jsFiddle

js小提琴