javascript jQuery 在文本字段上输入时按下按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17077777/
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
jQuery press button as enter on a text field
提问by Perocat
I have this text field:
我有这个文本字段:
<input id="address" type="text" value="">
and this button:
和这个按钮:
<input id="ricerca" type="button" class="enter" value="GO!">
and jQuery:
和 jQuery:
$("#ricerca").click(function(){
var e = jQuery.Event('keypress');
e.which = 13; // #13 = Enter key
$("#address").focus();
$("#address").trigger(e);
});
I want to simulate the "Enter" press INSIDE the #address
field, by clicking on the #ricerca
button. It is necessary that the cursor is inside the #address
field when I press the button.
我想#address
通过单击#ricerca
按钮来模拟在字段内按“Enter” 。#address
当我按下按钮时,光标必须在字段内。
Can you please say me where are the errors?
你能告诉我错误在哪里吗?
回答by Praveen Lobo
define what should happen on keypress event for #address
. Look at this code. Press enter key from insde the text box and then click on the button, both trigger the keypress event.
定义 .keypress 事件应该发生什么#address
。看看这段代码。在文本框中按回车键,然后单击按钮,两者都会触发按键事件。
demo - http://jsbin.com/ocohev/1/edit
演示 - http://jsbin.com/ocohev/1/edit
$(function () {
$('#address').keypress(function (event) {
if (event.which == 13) {
alert("enter pressed");
//return false; only if needed
}
});
$("#ricerca").click(function () {
var e = jQuery.Event('keypress');
e.which = 13; // #13 = Enter key
$("#address").focus();
$("#address").trigger(e);
});
});
回答by Venkatasubbaiah Gonepudi
Use this Jquery code:
使用此 Jquery 代码:
$("#id_of_textbox").keyup(function(event){
if(event.keyCode == 13){
$("#id_of_button").click();
}
});