Assigning a click-event-handler inside a click-event

左心房为你撑大大i 提交于 2021-02-07 11:37:30

问题


I have encountered some strange behavior when dealing with click-events in jQuery.

Have a look at this Fiddle

$('#button').click(function() {
    $(document).one('click', function() {
        alert('clicked');
    });
});

This code is binding a click-event-handler to some button. On clicking this link, an event-handler should be added to the document, alerting "clicked" when the document is next clicked.

But when clicking this button, "clicked" gets immediately alerted without another click. So apparently the click-event which binds the new handler to the document gets bubbled to the document and immediately runs the just assigned hndler.

This behavior seems very counter-intuitive. My intention was showing an element when clicking on the button and hiding it again on clicking outside this element.

$('#button').click(function() {
    // Show some element

    $(document).one('click', function() {
        // Hide the element again
    });
});

But this results in the element being hidden immediately.

Does anyone have a solution to this problem?


回答1:


The event can be prevented from propagating up the DOM.

$('#button').click(function(e) {
    e.stopPropagation();
    $(document).one('click', function(e) {
        alert('clicked');
    });
});

JS Fiddle: http://jsfiddle.net/7ymJX/6/




回答2:


can you please check this code Demo

HTML Code

<button id="button">Click me!</button>
<div id="new_div"></div>

Jquery

$('#button').click(function(e) {   
    e.stopPropagation();   
    $('#new_div').css('display', 'block');
    $('document, html').click( function() {
        alert('clicked');   
        $('#new_div').css('display', 'none');       
    });
});

Css

#new_div { 
    height: 100px;
    width: 200px;
    border:1px solid black;
    display : none;
}



回答3:


Stop it going to bubble with stopPropagation :)

edited fiddle with element hiding incorporated.

http://jsfiddle.net/AdamMartin121/7ymJX/12/



来源:https://stackoverflow.com/questions/18736271/assigning-a-click-event-handler-inside-a-click-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!