简体   繁体   中英

jQuery bind() - Prevent HTML click event from firing if LI click event fires

In my js, I have two click bindings:

$('#menu > li').bind('click', function () {...});

and

$('html').bind('click', function () {...});

They each do something slightly different depending on which is clicked. The problem is, a click on an LI is also a click on HTML, so when I click on LI, both the LI click and HTML click events fire.

If I click anywhere other than an LI, I get only the HTML click, as desired.

Is there any way to say, basically, " If the user clicked on an LI element, do this. Else, if the user clicked anywhere else other than an LI, do that "?

All you need to do is prevent event bubbling. Using jQuery it's as simple as adding e.stopPropagation() inside your li event handler.

So your updated code would look like this:

$('#menu > li').bind('click', function (e) {
    e.stopPropagation();
    ...
});

Further Reading:

https://api.jquery.com/event.stoppropagation/

http://www.quirksmode.org/js/events_order.html

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