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

时间:2012-08-17 19:14:00

标签: jquery dialog show-hide

我在使用按钮时遇到了一些问题,单击该按钮会激活弹出菜单。弹出菜单时,如果再次单击该按钮,弹出窗口就会消失。但是,如果您重新单击该按钮,则菜单不显示直到我点击按钮外的某处。我认为问题在于单击事件以及选择器是“html”,它将事件绑定到。有什么想法吗?

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

2 个答案:

答案 0 :(得分:1)

我认为你遇到了javascript事件的冒泡效应问题。当您单击某个按钮时,他的click事件首先被触发,然后是其父事件之一,从DOM一直到文档根目录。我认为你的解决方案可能是从jQuery应用stopPropagation函数。我在这里设置了一个小例子:http://jsfiddle.net/FF73h/

由于代码很少,我也会在这里通过它: HTML

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

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

我认为代码应该解释自己。如果没有,请随时告诉我。

答案 1 :(得分:0)

您是否尝试过使用body而不是html

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