1

要素のクラス属性の値を取得したい。

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

this.idthis.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
   });    
});
4

3 に答える 3

7

this.className代わりにあるはずだからです。

参照: https://developer.mozilla.org/en-US/docs/DOM/element.className

于 2013-04-12T12:03:47.337 に答える
2

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
   });    
});
于 2013-04-12T12:03:52.057 に答える
1

属性は、DOM のプロパティ (存在しないプロパティではない) にマップさclassれます。classNameclass

于 2013-04-12T12:03:25.457 に答える