keydown覆盖返回键的事件在Firefox中不起作用 [英] keydown Event to override return key does not work in Firefox
问题描述
我有以下简单的JavaScript代码,它处理返回键,我不想提交表单时,在文本框中按下返回键。
所有这些工作正常,但在Firefox中,如果我显示警告消息,则停止工作,表单开始提交,而没有提示消息的确切代码工作正常,并停止提交表单。我不明白为什么警报是破坏派对..
$(document)。ready(function(){
$(#input1)。keydown(OnKeyDown);
});
函数OnKeyDown(e){
if(e.keyCode == 13){
// alert('this will fail') ; //添加alert使表单提交
stopBubble(e);
返回false;
函数stopBubble(e){
//如果提供了一个事件对象,那么这是一个非IE浏览器
if(e& e.stopPagagation)
//因此它支持W3C stopPropagation()方法
e.stopPropagation();
else
//否则,我们需要使用Internet Explorer
//取消事件冒泡的方法
window.event.cancelBubble = true;
}
< input type =textid =input1value =>
我不知道事件是否正常或不。但是,这是我必须这样做,因为它在所有的浏览器中工作:
$ $ p $ $(code)$(无论).keypress(函数( e){
var k = e.keyCode || e.which;
if(k == 13){
return false; // !!!
}
});
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.
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..
$("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="">
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; // !!!
}
});
这篇关于keydown覆盖返回键的事件在Firefox中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!