jQuery click event on parent, but finding the child (clicked) element

前端 未结 3 1869
萌比男神i
萌比男神i 2020-12-05 04:09

let say I have a parent element which has so many nested child elements inside of itself:

相关标签:
3条回答
  • 2020-12-05 04:46

    You need to pass event object to function to get the item that triggered the event, event.target will give you the source element.

    Live Demo

     $('#p').bind('click', function(event) {
        alert(event.target.id);
     });
    

    or

    Live Demo

    $('#p').bind('click', function(event) {
        alert($(event.target).attr('id'));
    });
    

    Edit

    The first method event.target.id is preferred over second $(event.target).attr('id') for performance, simplicity and readability.

    0 讨论(0)
  • 2020-12-05 05:01

    You can try the below code. Also try the jsfiddle too(demo).

    $('#p').on('click', function(event) {
        alert(event.target.id);
    });​
    

    Try the demo

    The answer to your second question is you can assign event to the child and remove from it's parent. Check this out.

    .stopPropagation(); 
    

    Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. Read more

    if you want the specific event to be executed only and allow no other event to be fired you use code below

    event.stopImmediatePropagation()
    

    Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree. Read more

    I hope this will solve your problem. If you have any questions please don't hesitate to ask. Thanks

    0 讨论(0)
  • 2020-12-05 05:11

    If your elements have grandchildren, there is a better way to get just the child. Note the greater than sign.

    $('.parent > .child').click(function() {
        // This will be the child even if grandchild is clicked
        console.log($(this));
    });
    
    0 讨论(0)
提交回复
热议问题