javascript 在点击事件中分配点击事件处理程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18736271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Assigning a click-event-handler inside a click-event
提问by Lars Ebert
I have encountered some strange behavior when dealing with click-events in jQuery.
在处理 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?
有没有人有解决这个问题的方法?
回答by Kevin Bowersox
The event can be prevented from propagating up the DOM.
可以阻止事件传播 DOM。
$('#button').click(function(e) {
e.stopPropagation();
$(document).one('click', function(e) {
alert('clicked');
});
});
JS Fiddle:http://jsfiddle.net/7ymJX/6/
JS小提琴:http : //jsfiddle.net/7ymJX/6/
回答by Lars Ebert
Stop it going to bubble with stopPropagation
:)
阻止它冒泡stopPropagation
:)
edited fiddle with element hiding incorporated.
编辑小提琴与元素隐藏合并。
回答by Shakti Patel
can you please check this code Demo
你能检查一下这个代码演示吗
HTML Code
HTML代码
<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
css
#new_div {
height: 100px;
width: 200px;
border:1px solid black;
display : none;
}