如何使用jquery触发文本字段上的键盘点击事件
我想单击 Enter 而不是提交按钮,并且我希望 jquery 执行与单击提交按钮完全相同的任务。
这是我所拥有的,但它不适用于
jquery
$("#search-friend-text").keypress(function(e){ // start enter click
switch(e){
case 13:
$.post("<?php echo site_url('userProfile/search_friend'); ?>",
$("#add-friend-search").serialize(),
function(data){
$("#insert-activity").html(data);
});
$("#add-friend-search").slideUp("slow",function(){});
break;
}
}); // end enter click
Html(表单)
<form method="post" action="" name="searchFriendForm" id="add-friend-search">
<input type="text" id="search-friend-text" name="searchFriendText">
<input type="button" class="small green button" id="add-friend-button" />
</form>
I want to click enter instead of submit button and I want jquery to do the exact same task as if I were clicking the submit button.
This is what I have but its not working
the jquery
$("#search-friend-text").keypress(function(e){ // start enter click
switch(e){
case 13:
$.post("<?php echo site_url('userProfile/search_friend'); ?>",
$("#add-friend-search").serialize(),
function(data){
$("#insert-activity").html(data);
});
$("#add-friend-search").slideUp("slow",function(){});
break;
}
}); // end enter click
the Html (form)
<form method="post" action="" name="searchFriendForm" id="add-friend-search">
<input type="text" id="search-friend-text" name="searchFriendText">
<input type="button" class="small green button" id="add-friend-button" />
</form>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
使用 e.keyCode :
use e.keyCode :
首先,正如 Vlad 所指出的,您需要为开关提供编号,而不是事件对象。其次,如果您只想查找一个号码,则无需使用开关/外壳。试试这个:
First off as Vlad has pointed out, you need to provide the switch with the number and not the event object. Secondly, if you are only going to look for one number, there isn't a need to use the switch/case. Try this:
我认为这可以解决这个问题
,因为
e
是事件处理程序I think this will solve it
Since
e
is the event handler您应该使用提交事件。
You should use the submit event.
您在按键中收到的事件是一个事件对象,因此我不确定您的 switch/case 语句是否会起作用!您只需调用 $("target").keypress( e ) 即可触发项目的按键事件 - 其中 e 是您需要构建的事件,其中包含字符键码(您必须将其设置为事件.which )
The event you receive in your keypress is an event object so i'm not sure your switch/case statement would work anyway! and you can trigger a keypress event for an item by simply invoking $("target").keypress( e ) -- where e is an event you need to build that has the character keycode in it ( you will have to set it in evet.which )
好吧,你可以看看 jQuery 中的这个函数: triggerHandler
但实际上,最好移动一下您的点击事件代码放入一个单独的函数中,您可以从点击事件和按键事件中调用该函数。
Well you can take a look at this function in jQuery: triggerHandler
But really, it might be better to move your click event code into a separate function which you can call from the click event and from the keypress event.