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

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

    If a child element is clicked, then the event bubbles up to the parent and event.target !== event.currentTarget.

    So in your function, you can check this and return early, i.e.:

    var url = $("#clickable a").attr("href");
    $("#clickable").click(function(event) {
        if ( event.target !== event.currentTarget ){
            // user clicked on a child and we ignore that
            return;
        }
        window.location = url;
        return true;
    })
    

提交回复
热议问题