开发者

jQuery, discover what a dom object's class are

I have a .click() on several buttons. Each .click() calls a function. The function needs to know which button called it so that it can show or hide different content and change the styles of the other buttons. The function has an event object passed to it.

Is there a way I can get the current class that the event 开发者_开发百科object has?


$('myButton').click(function() {
    var className = this.className; // This will give you the whole class string of the clicked element
    var hasClass = $(this).hasClass('myClass'); // This will tell you (true or false) whether the clicked element has class 'myClass'
});


You can get the class with .className or .attr("class"), though what you probably want is to have this refer to the button, for example:

$(".selector").click(myFunction);

function myFunction() {
  //this == button that was clicked
  var c = this.className;
}

Or an inline function:

$(".selector").click(function () {
  var c = this.className;
});


As long as you are passing this to a function (though depending how you are doing this, some code would be nice!), if you pass e as the first parameter in the function then you can use e.target.className to get the class, or, with jQuery $(e.target).attr('class');


Couldn't you make different functions for the different .click() calls?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜