[英]How to stop alert box press enter loop?
When the user presses enter on the document, I show an alert box with alert()
. 当用户在文档上按Enter键时,我会显示一个带
alert()
的警告框。
The default behaviour the browser (Chrome 27 on Mac OS X 10.8.4) has is when you press enter when focused on the alert box, it will close it. 浏览器(Mac OS X 10.8.4上的Chrome 27)的默认行为是当您将注意力集中在警告框上时按Enter键,它将关闭它。 That will trigger the enter on the document, showing the alert box again.
这将触发文档上的输入,再次显示警告框。 You can see how it can loop.
你可以看到它如何循环。
Note that when I use my mouse to click OK in the alert box, the loop does not happen. 请注意,当我使用鼠标在警告框中单击“确定”时,循环不会发生。
How can I prevent this looping? 如何防止这种循环?
An example (the real way I use this is a lot more complicated): 一个例子(我使用它的真实方式要复杂得多):
$(document).keyup(function(e) {
e.preventDefault();
var keyCode = e.keyCode || e.which;
if (keyCode == 13) {
alert('Hello world!');
}
return false;
});
you can delegate the keydown
event and use stopPropagation()
to prevent the event from bubbling up to the document when it is triggered on the alert dialog, like so: http://jsfiddle.net/KNyzc/ 您可以委派
keydown
事件并使用stopPropagation()
来防止事件在警告对话框中触发时冒泡到文档,如下所示: http : //jsfiddle.net/KNyzc/
$(document).on( "keydown", function(e) {
e.stopPropagation();
var keyCode = e.keyCode || e.which;
if (keyCode == 13) {
alert('Hello world!');
}
});
( actually, you don't need to use stopPropagation
at all. Just use the keydown event. ) (实际上,你根本不需要使用
stopPropagation
。只需使用keydown事件。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.