javascript 用于覆盖返回键的 keydown 事件在 Firefox 中不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3859748/
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
keydown Event to override return key does not work in Firefox
提问by ace
I have the following simple javascript code, which handles the Return Key, I don't want to submit the form when the return key is pressed in the textbox.
我有以下简单的 javascript 代码,它处理返回键,我不想在文本框中按下返回键时提交表单。
All this works fine, but in Firefox, if i show an alert message, then it stops working and the form starts getting submitted, whereas the exact code without alert message works fine and stops the form from being submitted. I dont understand why alert is spoiling the party..
所有这些都可以正常工作,但是在 Firefox 中,如果我显示一条警报消息,它就会停止工作并且表单开始被提交,而没有警报消息的确切代码可以正常工作并停止提交表单。我不明白为什么警报会破坏派对..
$("document").ready(function () {
$("#input1").keydown(OnKeyDown);
});
function OnKeyDown(e) {
if (e.keyCode == 13) {
// alert('this will fail'); // Adding alert makes the form submit
stopBubble(e);
return false;
}
}
function stopBubble (e) {
// If an event object is provided, then this is a non-IE browser
if (e && e.stopPropagation)
// and therefore it supports the W3C stopPropagation() method
e.stopPropagation();
else
// Otherwise, we need to use the Internet Explorer
// way of cancelling event bubbling
window.event.cancelBubble = true;
}
<input type="text" id="input1" value="">
回答by Gregg
I don't really know if the event is normalized or not. But this is how I have to do it for it to work in all browsers:
我真的不知道事件是否正常化。但这就是我必须这样做才能在所有浏览器中工作的方法:
$(whatever).keypress(function (e) {
var k = e.keyCode || e.which;
if (k == 13) {
return false; // !!!
}
});
回答by Nick Craver
jQuery normalizes this already, you can just do:
jQuery 已经对此进行了规范化,您可以这样做:
$(document).ready(function () {
$("#input1").keydown(OnKeyDown);
});
function OnKeyDown(e) {
if (e.which == 13) { //e.which is also normalized
alert('this will fail');
return false;
}
}
When you do return falsefrom a handler, jQuery calls event.preventDefault()and event.stopPropgation()internally already. You can also do the anonymous function version:
当您return false从处理程序执行此操作时,jQuery 会在内部调用event.preventDefault()和event.stopPropgation(). 您还可以执行匿名函数版本:
$(function () {
$("#input1").keydown(function() {
if (e.which == 13) return false;
});
});
回答by Basil
textBox.onkeydown = function (e) {
e = e || window.event;
if (e.keyCode == 13) {
if (typeof (e.preventDefault) == 'function') e.preventDefault();
if (typeof (e.stopPropagation) == 'function') e.stopPropagation();
if (typeof (e.stopImmediatePropagation) == 'function') e.stopImmediatePropagation();
e.cancelBubble = true;
return false;
}
}

