繁体   English   中英

如何获取元素的class属性?

[英]How to get the class attribute of an element?

我想获取元素的class属性的值。

<a href="http://stackoverflow.com/" id="myId" class="myClassName">Click Me</a>

this.idthis.hrefthis.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM