[英]jQuery keypress event trigger not working on page load
I am trying to simulate an enter keypress for an input on page load, however it doesn't appear to be working. 我正在尝试为页面加载上的输入模拟Enter键,但是它似乎不起作用。 I only find success when I click in the input and press enter.
我只有在单击输入并按Enter时才能找到成功。 I expect to see the alert when the page loads.
我希望在页面加载时看到警报。
If you change the order I have listed below, then it provides an alert, but the key that is pressed is undefined. 如果您更改了我在下面列出的顺序,那么它将提供警报,但是所按下的键是不确定的。
Any ideas where I am going wrong here? 有什么想法我在这里出错吗?
See demo here - http://jsfiddle.net/3xTM2/1321/ 在此处查看演示-http: //jsfiddle.net/3xTM2/1321/
HTML 的HTML
<input id="test" type="text" />
Javascript Java脚本
$('#test').trigger(jQuery.Event('keypress', { keycode: 13 }));
$('#test').keypress(function(e) {
alert(e.keyCode);
});
As mentioned in the comment, just change the order and change keycode
to keyCode
as below. 如评论中所述,只需更改顺序并将
keycode
更改为keyCode
,如下所示。
Note : Please note the upper case in Code
instead of lower case in code
注 :请注意,在上壳中
Code
,而不是小写code
$('#test').keypress(function(e) { alert(e.keyCode); }); $('#test').trigger(jQuery.Event('keypress', { keyCode: 13 }));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="test" type="text" />
You have to reverse the order, and assign the data to the event object on your version of jQuery: 您必须颠倒顺序,然后将数据分配给jQuery版本的事件对象:
$('#test').keypress(function(e) {
alert(e.keyCode);
});
var event = jQuery.Event('keypress');
event.keyCode = 13;
$('#test').trigger(event);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.