[英]How to get the class attribute of an element?
我想获取元素的class属性的值。
<a href="http://stackoverflow.com/" id="myId" class="myClassName">Click Me</a>
this.id
, this.href
和this.text
工作。
我的问题是为什么this.class
无法正常工作?
注意:
我不想使用:
console.log($this.attr('class'));
或console.log($("a").prop("class"));
因为它很慢。
$(function(){
$("a").on("click",function(){
console.log(this.id); // myId
console.log(this.href); // http://stackoverflow.com/
console.log(this.text); // Click Me
console.log($("a").prop("class")); // myClassName
});
});
因为它应该是this.className
代替。
参考: https : //developer.mozilla.org/en-US/docs/DOM/element.className
使用this.className
是本机javascript元素属性。
$(function(){
$("a").on("click",function(){
console.log(this.id); // myId
console.log(this.href); // http://stackoverflow.com/
console.log(this.text); // Click Me
console.log(this.className); // myClassName
});
});
class
属性映射到DOM中的className
属性(不是不存在的class
属性)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.