如何在文本框中获取 Enter 键以触发功能而不是第一个/默认按钮 [英] How to get the Enter key within a textbox to trigger a function and not the first/default button

查看:9
本文介绍了如何在文本框中获取 Enter 键以触发功能而不是第一个/默认按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to get the Enter key to trigger a function when it is pressed when inside a certain textbox, and not trigger the first or default button.

您可以在此处查看正在发生的事情的示例:http://jsfiddle.net/cutsomeat/WZ6TM/1/

You can see an example of what is happening here: http://jsfiddle.net/cutsomeat/WZ6TM/1/

如果您按其他键,您将看到带有键码的警报框,但如果您按 Enter 键,您将不会获得带有键码的警报框,而是按钮单击事件中的警报框.

If you press other keys you will get an alert box with the keycode, yet if you press the Enter key you will not get the alert box with the keycode, but rather the alert box within the button click event.

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

Obviously the Enter key is trigger the button. Is there a way to avoid this and instead, capture the Enter key in the keyup event, then trigger another function?

推荐答案

试试这个:

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

演示

这篇关于如何在文本框中获取 Enter 键以触发功能而不是第一个/默认按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆