stopPropagation() preventing childs onClick functi

2019-08-01 01:26发布

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?

2条回答
孤傲高冷的网名
2楼-- · 2019-08-01 02:15

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();
});
查看更多
女痞
3楼-- · 2019-08-01 02:22

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.)

查看更多
登录 后发表回答