开发者

How to select class properties via jQuery

This is the HTML in question:

<a href="#" cla开发者_StackOverflow中文版ss="a01">xxx a01</a>
<a href="#" class="b02">xxx a021</a>
<a href="#" class="c03">xxx aa021</a>
<a href="#" class="d04">xxx aaa2021</a>

On click on a link, jQuery:

$("a").click(function(){
   alert($(this).html()); // we get xxx a01 , xxx a021 and so on..
})

How do I get the class value, such as a01, b02, c03 and so on?

thanks.


Use this.className, it's faster and less redundant than $(this).attr("class").

$("a").click(function(){
    alert(this.className);
});
  • element.className - Mozilla Developer Network


Most attributes are directly accessible as properties of the element, so wrapping jQuery around this and using attr() or prop() are generally unnecessary.

Read more on this at http://whattheheadsaid.com/2010/10/utilizing-the-awesome-power-of-jquery-to-access-properties-of-an-element (plug).


You can use jQuery's .attr() method in order to retrieve any attribute from an element.

$(this).attr("class")


alert($(this).attr('class'));

http://api.jquery.com/attr/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜