简体   繁体   中英

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. 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. 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. I think the solution for you might be to apply the stopPropagation function from jQuery. I set up a small example here: http://jsfiddle.net/FF73h/

Since it's so little code I'll past it here as well: 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();            
});

I think the code should explain itself. If not, feel free to let me know.

Have you tried using body rather than html ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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