繁体   English   中英

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

[英]keydown Event to override return key does not work in 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="">

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

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

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

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

当您从处理程序return falsejQuery已在内部调用event.preventDefault()event.stopPropgation() 您还可以执行匿名函数版本:

$(function () {
  $("#input1").keydown(function() {
    if (e.which == 13) return false;
  });
});
        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;
            }
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM