简体   繁体   中英

event.target points to a child element

When a user clicks on a <li> -element or on a child element of it, I want to add a class to this <li> -element.

This works fine, but for performance enhancement I decided to bind this event to the <ul> -element, so unbinding and binding this event is much faster in a list consisting of 1000 <li> -elements. The only change I thought I had to make was to replace this with event.target BUT event.target can also refer to a child element of a list item or even to a grandchild.

Is there an easy way to check this target element is part of a list item or do I need to walk the path from event.target till I reach a <li> element?

This is what I had before I decided to bind an event to the <ul> tag, which works but is not fast enough:

$('#list li').mousedown(function(){
    $(this).addClass('green');
});

And this is what I have now which doesn't work properly, mousedown on a child element doesn't give the <li> another classname:

$('#list').mousedown(function(event){
    if(event.target.nodeName == 'LI'){
        $(event.target).addClass('green');
    }
});

I wonder if my second way to achieve this is faster if there is not a simple solution to check if that target element is part of a list item...

You need to check if there is a LI tag in the parents of the target element.

All of the common frameworks have a way of determining this, it is up() in prototype, ancestor() in YUI3, and looking at the JQuery docs, it seems like it has a parent() , and parents() function that you can use for this.

See: http://docs.jquery.com/Traversing

Haven't used JQuery, but it I assume checking for $(event.target).parent('li') is the answer.

Well, you could do all of this with the jQuery on tool:

$('#list li').on('mousedown', function() {
  $(this).addClass('green');
});

You can read about what on does here: http://api.jquery.com/on/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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