stopPropagation() preventing childs onClick functions

纵饮孤独 提交于 2019-12-11 11:59:46

问题


I've searched everywhere and I couldn't find an answer to this question.

I've built a menu with couple of divs inside divs:

<nav id="menu">
   <span>Open Menu</span>

   <div class="dropdownContain">
       <div class="dropOut">
          ...
          ...
          <div id="logout_wrap">
             <a id="logout">

And a script using JQuery so that menu appears (toggle) when "#menu" is clicked and disappear when body is clicked. for this functionality I had to use stopPropagation() method to stop #dropDownContain from running "body" 's hide() function

$(document).ready(function () {

    $('#menu').click(function (e) {
        e.stopPropagation();
        $('.dropdownContain').toggle();
    });

    $(document).click(function (e) {
        $('.dropdownContain').hide();
    });

    $('.dropdownContain').click(function (e) {
        e.stopPropagation();
    });

also I have made a click event for "#logout" which is inside "#dropdownContain" (which is the main body of menu) to run someThing() function.

jQuery('body').on('click', '#logout', function () {
    alert("THIS DOES NOT WORK");
});

The problem is that "#logout" 's assigned function will not fire because of the stopPropagation() method that is called in it's parent (or so I think).

here's the link to html + js for this code, just so you could see it in use: JSFiddle

so is there a solution to fix this while keeping the menu popup working as explained?


回答1:


Stop using stopPropagation and manually check if the click was inside #menu or not :

$('#menu').on('click', function() {
    $('.dropdownContain').toggle();
});

$(document).on('click', function(e) {
    if (! $(e.target).is('#menu') || $(e.target).closest('#menu').length )
        $('.dropdownContain').hide();
});



回答2:


Unless you have a reason for using event delegation, you can just bind the click directly to the logout link.

jQuery('#logout').on('click', function () {
    alert("this works");
});

The delegated version you were using only fires when the event bubbles all the way back to the body element (which it won't, since you're stopping the propagation.)



来源:https://stackoverflow.com/questions/15531126/stoppropagation-preventing-childs-onclick-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!