JQuery 1.3.2 - Best way to prevent events from firing on lower elements?

I have this (simplification):

$(li).click(function{alert("test");});

<li>
   <input>
</li>

What is the best way to bind an event to li, but not fire when the user clicks on an element input?

+3
source share
3 answers

Try using the stopPropagation method of the Event object.

$('input').click(function(event) {
    event.stopPropagation();
});

You can also target specific children (or direct children) liusing a combination of selectors:

$('li > input, li strong, li span').click( ... );
+6
source

In one solution can be used event.target.

In the event handler, use

if( $(event.target).is('input') )
    return;
+2
source

, .

$(li).click(function(e) {
    if ($(e.target).is("input")) {
        alert("Test");
    }
});
+2

Source: https://habr.com/ru/post/1741161/


All Articles