简体   繁体   中英

Multiple OnClick JQuery events firing

I have a page with div and a button on it. I have added onClick event to both of them. Now when I click the button on the div the onClick of the div is also being executed. Is there any way that I can avoid this?

Thank You,

Try this, pass the event as parameter to your onclick event and call

event.stopPropagation();
event.preventDefault();

Your onclick event assignment should be:

$(button).click(function(event) {
    // script here
    event.stopPropagation();
    event.preventDefault();
});

In your click handler you might want to use "stopPropagation" for example:

$("button").click(function(e) {
    // handle this event
    // ...

    // don't pass this event up to parent handlers
    e.stopPropagation();

} );

There's also a related function that you might want to read about called "preventDefault" which tells the browser not to do what it normally does automatically (eg submit a page when a submit button is clicked)

See also: https://developer.mozilla.org/en/DOM/event.stopPropagation http://api.jquery.com/event.stopPropagation/ What's the effect of adding 'return false' to a click event listener? http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/

in the listener for the link element, you can put e.stopPropagation() , which should fix it (if you're using event bubbling).

If you aren't using jQuery, make sure you set the useCapture parameter of addEventListener() to False info - MDN ; you want to be sure you know which direction your events are moving through the DOM (you want them to bubble).

You need to prevent the button onClick event from bubbling to the Div. So basically at the end of your onClick function for the button, once you have done all you logic, you need to call event.stopPropagation()

If none of the above work, try out:

$("button").click(function(e) {
    e.stopImmediatePropagation();
});

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