How to stop propagating event from parent div to child div

前端 未结 5 1952
一向
一向 2021-02-20 01:36

I want to stop propagate event from parent div to child div in my html. Here a simple code what I\'m trying to do:

5条回答
  •  孤独总比滥情好
    2021-02-20 02:07

    The accepted answer is correct but in a best scenario when you have multiple nested elements, You would like to not cancel the event but to get the actual clicked parent container and work with it.

    $('.clicked-container').click((e) => {
        let t = e.target;
        while (!$(t).hasClass( "clicked-container" )) { t = t.parentNode; }
         
        ...
        $(t).toggleClass('active-or-whatever-you-want');
    });
    

    Also "this" in the accepted answer doesn't refer anymore to the same thing when you using Arrows => in ES6

提交回复
热议问题