jQuery 在“click”和“enter”上触发事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9146651/
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
Trigger an event on `click` and `enter`
提问by kirby
I have a searchbox on my site that. Currently, users must click the submit button next to the box to search via jquery's post. I would like to let users also press enter to search. How can i do this?
我的网站上有一个搜索框。目前,用户必须单击框旁边的提交按钮才能通过 jquery 的帖子进行搜索。我想让用户也按回车键进行搜索。我怎样才能做到这一点?
JQUERY:
查询:
$('document').ready(function(){
$('#searchButton').click(function(){
var search = $('#usersSearch').val();
$.post('../searchusers.php',{search: search},function(response){
$('#userSearchResultsTable').html(response);
});
});
});
HTML:
HTML:
<input type='text' id='usersSearch' /><input type='button' id='searchButton' value='search' />
回答by ShankarSangoli
Use keypress
event on usersSearch
textbox and look for Enterbutton. If enter button is pressed then trigger the search button click event which will do the rest of work. Try this.
keypress
在usersSearch
文本框上使用事件并查找Enter按钮。如果按下输入按钮,则触发搜索按钮单击事件,该事件将完成其余工作。尝试这个。
$('document').ready(function(){
$('#searchButton').click(function(){
var search = $('#usersSearch').val();
$.post('../searchusers.php',{search: search},function(response){
$('#userSearchResultsTable').html(response);
});
})
$('#usersSearch').keypress(function(e){
if(e.which == 13){//Enter key pressed
$('#searchButton').click();//Trigger search button click event
}
});
});
回答by Gustavo Rodrigues
You call both event listeners using .on()
then use a if
inside the function:
您使用.on()
然后if
在函数内部使用 a调用两个事件侦听器:
$(function(){
$('#searchButton').on('keypress click', function(e){
var search = $('#usersSearch').val();
if (e.which === 13 || e.type === 'click') {
$.post('../searchusers.php', {search: search}, function (response) {
$('#userSearchResultsTable').html(response);
});
}
});
});
回答by jopke
Something like this will work
像这样的东西会起作用
$('#usersSearch').keypress(function(ev){
if (ev.which === 13)
$('#searchButton').click();
});
回答by elclanrs
$('#form').keydown(function(e){
if (e.keyCode === 13) { // If Enter key pressed
$(this).trigger('submit');
}
});
回答by Asif Ghanchi
you can use below event of keypress on document load.
您可以在文档加载时使用以下按键事件。
$(document).keypress(function(e) {
if(e.which == 13) {
yourfunction();
}
});
Thanks
谢谢
回答by xandercoded
$('#usersSearch').keyup(function() { // handle keyup event on search input field
var key = e.which || e.keyCode; // store browser agnostic keycode
if(key == 13)
$(this).closest('form').submit(); // submit parent form
}