stopPropagation()防止孩子的onClick函数 [英] stopPropagation() preventing childs onClick functions

查看:104
本文介绍了stopPropagation()防止孩子的onClick函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我到处搜索,找不到该问题的答案.

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

我在div内建立了一个带有几个div的菜单:

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">

还有一个使用JQuery的脚本,以便在单击"#menu"时显示(切换)菜单,而在单击body时消失.为此功能,我必须使用stopPropagation()方法来阻止#dropDownContain运行"body"的hide()函数

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();
    });

我还为"#logout"(位于菜单的主体)内部的"#logout"创建了一个单击事件,以运行someThing()函数.

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");
});

问题在于"#logout"的分配函数由于在其父级(或我认为)中调用的stopPropagation()方法而不会触发.

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

这是此代码的html + js链接,以便您可以看到它的使用情况: JSFiddle

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?

推荐答案

使用stopPropagation停止,并手动检查单击是否在#menu内部:

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();
});

这篇关于stopPropagation()防止孩子的onClick函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆