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
Object [object HTMLAnchorElement] has no method 'attr'
提问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 this
reference is not a jquery
object.
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. .data
and .attr
are 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/
jsFiddle:http: //jsfiddle.net/hescano/pFdEj/
回答by Charlie
Something else is wrong in your page, then. The following doeswork:
那么,您的页面中还有其他问题。以下确实有效:
$(this).data("id")
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);
});
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"));
}
}