jQuery 如何在文本框中获取 Enter 键以触发功能而不是第一个/默认按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11001762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the Enter key within a textbox to trigger a function and not the first/default button
提问by MarkieB
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.
我试图让 Enter 键在某个文本框内被按下时触发一个功能,而不是触发第一个或默认按钮。
You can see an example of what is happening here: http://jsfiddle.net/cutsomeat/WZ6TM/1/
你可以看到这里发生的事情的一个例子:http: //jsfiddle.net/cutsomeat/WZ6TM/1/
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 键,您将不会看到带有键码的警告框,而是按钮单击事件中的警告框。
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?
显然 Enter 键是触发按钮。有没有办法避免这种情况,而是在 keyup 事件中捕获 Enter 键,然后触发另一个功能?
回答by sachleen
回答by Arvind Bhardwaj
Use .on()
as .live()
has been deprecated.
使用.on()
as.live()
已被弃用。
$(document).on("keypress", ".myText", function(e) {
if (e.which == 13) {
//do some stuff
}
});
回答by Suraj Chandran
Do e.preventDefault()
in keyDown to avoid default action of button:
做e.preventDefault()
在的keyDown避免按钮的默认操作:
$('#myText').keydown(function(e) {
if (e.keyCode == 13) {
e.preventDefault();
}
alert(e.keyCode);
});
回答by thecodeparadox
$(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!');
});
});
For live elements use .on()
like below:
对于实时元素,请使用.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!');
});
});