如何在文本框中获取Enter键以触发函数而不是第一个/默认按钮

问题描述 投票:38回答:4

我试图让Enter键在某个文本框内按下时触发一个函数,而不是触发第一个或默认按钮。

你可以看到这里发生的事情的一个例子:http://jsfiddle.net/cutsomeat/WZ6TM/1/

如果按其他键,您将收到一个带有键码的警告框,但是如果您按下Enter键,您将无法获得带有键码的警告框,而是按钮点击事件中的警告框。

显然,Enter键是触发按钮。有没有办法避免这种情况,而是在keyup事件中捕获Enter键,然后触发另一个函数?

jquery button textbox keycode enter
4个回答
82
投票

试试这个:

$('#myText').on("keypress", function(e) {
        if (e.keyCode == 13) {
            alert("Enter pressed");
            return false; // prevent the button click from happening
        }
});

Demo


49
投票

使用.on()作为.live()一直是deprecated

$(document).on("keypress", ".myText", function(e) {
     if (e.which == 13) {
         //do some stuff
     }
});

21
投票

在keyDown中执行e.preventDefault()以避免按钮的默认操作:

$('#myText').keydown(function(e) {
    if (e.keyCode == 13) {
        e.preventDefault();
    }
    alert(e.keyCode);
});

12
投票
$(document).ready(function() {

    $('#myText').keypress(function(e) {
        if ( e.keyCode == 13 ) {  // detect the enter key
            $('#myButton').click(); // fire a sample click,  you can do anything
        }
    });

    $('#myButton').click(function(e) {
        alert('Button click activated!');
    });

});

DEMO

对于实时元素,请使用.on(),如下所示:

$(document).ready(function() {

    $(document).on('keypress', '#myText', function(e) {

        if ( e.keyCode == 13 ) {  // detect the enter key
            $('#myButton').click(); // fire a sample click,  you can do anything
        }
    });

    $(document).on('click', '#myButton', function(e) {
        alert('Button click activated!');
    });

});
© www.soinside.com 2019 - 2024. All rights reserved.