最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery - Getting class of an element through the event.target property - Stack Overflow

programmeradmin4浏览0评论

I have the following code:

    <script type="text/javascript">
       $("*").click(function(event){
         var x = event.target;

         if (x.nodeName == "DIV"){                  
           alert(x.attr("class"));
         }

       })
    </script>

This throws an 'undefined' exception... Is there any other way to get the class of an element which triggered the 'click' event? Thank you in advance!

I have the following code:

    <script type="text/javascript">
       $("*").click(function(event){
         var x = event.target;

         if (x.nodeName == "DIV"){                  
           alert(x.attr("class"));
         }

       })
    </script>

This throws an 'undefined' exception... Is there any other way to get the class of an element which triggered the 'click' event? Thank you in advance!

Share Improve this question edited Jan 5, 2015 at 16:09 Johnny Bueti asked Oct 29, 2012 at 12:04 Johnny BuetiJohnny Bueti 6481 gold badge8 silver badges28 bronze badges 2
  • 3 Note that you don't have to refer to event.target, but you might as well just refer to this. if (this.nodeName == "DIV") alert( $(this).attr("class")); – h2ooooooo Commented Oct 29, 2012 at 12:07
  • 1 Well, using $('*') as selector, you shoud use event.stopPropagation() in your event callback function, just my 2 cents. – A. Wolff Commented Oct 29, 2012 at 12:18
Add a comment  | 

2 Answers 2

Reset to default 13

event.target is a DOM object. So to use jQuery methods you have to convert it to jQuery object:

alert($(x).attr("class"));

Otherwise, you may use property className to get the class of the element:

alert(x.className);

BTW, in your example you may simply use this keyword instead of event.target.

jQuery offers some syntactic sugar to help with your check - .is() allows you to validate an element against any other valid selector:

var $target = event.target;
if ($target.is('div')){
  alert($target.attr('class'));
}

There are some further changes to consider:

  • .click(handler) is explicitly assigned to the matching elements (every single element in your case). This adds overhead; also the handler will not apply to any element added dynamically after the handler assignment is executed. Instead, delegate the handler by using on()
  • refactor your logic so that instead of handling every single click and validating it you could make it applicable only to divs in the first place by changing the selector to $('div')
  • rely on this which is pretty much the convention

After all these changes the code becomes smaller and more readable:

$('div').on('click', function() {
  alert($(this).attr('class'));
});
发布评论

评论列表(0)

  1. 暂无评论