keydown覆盖返回键的事件在Firefox中不起作用

时间:2010-10-04 22:54:53

标签: javascript jquery firefox

我有以下简单的javascript代码,它处理返回键,我不想在文本框中按下返回键时提交表单。

所有这一切都运行正常,但在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="">

3 个答案:

答案 0 :(得分:4)

我真的不知道事件是否正常化。但是我必须这样做才能在所有浏览器中使用它:

$(whatever).keypress(function (e) {

    var k = e.keyCode || e.which;
    if (k == 13) {
        return false; // !!!
    }
});

答案 1 :(得分:2)

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;
    }
}

当您从处理程序jQuery calls event.preventDefault() and event.stopPropgation() internally already执行return false时。您也可以使用匿名函数版本:

$(function () {
  $("#input1").keydown(function() {
    if (e.which == 13) return false;
  });
});

答案 2 :(得分:0)

        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;
            }
        }