简体   繁体   English

单击一次打开/关闭后,不会触发Click事件

[英]Click Event Doesn't Fire After Clicking On/Off One Time

I am having some trouble with a button which when clicked, activates a popup menu. 我在使用按钮时遇到了麻烦,单击该按钮会激活弹出菜单。 When the menu is popped up, if you click the button again, the popup goes away. 弹出菜单后,如果再次单击该按钮,则弹出窗口消失。 But if you re-click the button, the menu doesn't show up UNTIL I click somewhere outside of the button. 但是,如果您重新单击该按钮,则在我单击按钮之外的某个位置之前,菜单不会显示。 I believe the issue lies with the one click event along with the selector being "html" which it binds the event to. 我认为问题在于单击事件以及将事件绑定到的“ html”选择器。 Any ideas? 有任何想法吗?

GetDropDownButton: function (option, thisId) {
        var menu = $('#' + option);
        // shows the popup
        menu.show();

        setTimeout(function () {
            // idea is to click anywhere to allow popup to close
            $('html').one('click', function () {
                // hides the popup
                menu.hide();
            });
        }, 100);
    },

I think you are experiencing problems with the bubbling effect of javascript events. 我认为您在遇到javascript事件冒泡效果时遇到了问题。 When you click on a button, his click event gets triggered first, then the one of its parent, all the way up the DOM to the document root. 当您单击一个按钮时,将首先触发他的click事件,然后触发其父事件,直到DOM一直到文档根目录。 I think the solution for you might be to apply the stopPropagation function from jQuery. 我认为您的解决方案可能是应用jQuery的stopPropagation函数。 I set up a small example here: http://jsfiddle.net/FF73h/ 我在这里设置了一个小示例: http : //jsfiddle.net/FF73h/

Since it's so little code I'll past it here as well: HTML 由于代码太少,我也将其粘贴在这里:HTML

<div class="popup">
    popup!
</div>
<button class="btn-toggle">on/off</button>​

JS JS

// make the button show/hide the popup
$('.btn-toggle').click(function(e) {
    $('.popup').toggle(); 
    // prevent the handler for the document to be called as well, wich would hide again
    e.stopPropagation();  
});
// make the popup close when clicked anywhere in the document
$(document).click(function() {
    $('.popup').hide();
});
// optional: prevent the popup from closing when clicked inside it, stops the ducoment event from beeing called
$('.popup').click(function(e) {
    e.stopPropagation();            
});

I think the code should explain itself. 我认为代码应该自我解释。 If not, feel free to let me know. 如果没有,请随时告诉我。

Have you tried using body rather than html ? 您是否尝试过使用body而不是html

 $('body').one('click', function () {
    // hides the popup
    menu.hide();
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM