How do I prevent a parent's onclick event from firing when a child anchor is clicked?

后端 未结 22 1416
旧巷少年郎
旧巷少年郎 2020-11-22 00:37

I\'m currently using jQuery to make a div clickable and in this div I also have anchors. The problem I\'m running into is that when I click on an anchor both click events ar

22条回答
  •  一整个雨季
    2020-11-22 01:23

    Use stopPropagation method, see an example:

    $("#clickable a").click(function(e) {
       e.stopPropagation();
    });
    

    As said by jQuery Docs:

    stopPropagation method prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

    Keep in mind that it does not prevent others listeners to handle this event(ex. more than one click handler for a button), if it is not the desired effect, you must use stopImmediatePropagation instead.

提交回复
热议问题