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

后端 未结 22 1381
旧巷少年郎
旧巷少年郎 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:21

    Events bubble to the highest point in the DOM at which a click event has been attached. So in your example, even if you didn't have any other explicitly clickable elements in the div, every child element of the div would bubble their click event up the DOM to until the DIV's click event handler catches it.

    There are two solutions to this is to check to see who actually originated the event. jQuery passes an eventargs object along with the event:

    $("#clickable").click(function(e) {
        var senderElement = e.target;
        // Check if sender is the 
    element e.g. // if($(e.target).is("div")) { window.location = url; return true; });

    You can also attach a click event handler to your links which tell them to stop event bubbling after their own handler executes:

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

提交回复
热议问题