简体   繁体   English

jQuery模拟输入的按键

[英]jQuery simulate keypress on input

I tried the answer here but it doesn't work for me. 我在这里尝试了答案但对我不起作用。

JSFiddle: https://jsfiddle.net/Ldu6wwv0/ JSFiddle: https ://jsfiddle.net/Ldu6wwv0/

$('input').val('test').trigger(jQuery.Event('keypress', {keycode: 13}));

$('input').on('keypress', function(){
    $('p').text("worked");
});

What am I doing wrong? 我究竟做错了什么?

The problem seems to be order of your code. 问题似乎出在您的代码顺序上。 Your code which triggers keypress is defined before the event handler. 触发按键的代码是在事件处理程序之前定义的。

This seems to work now. 现在看来这可行。 ( JSFiddle ) JSFiddle

$('input').on('keypress', function(){
    $('p').text("worked");
});

$('input').val('test').trigger(jQuery.Event('keypress', {keycode: 13}));

UPDATE: Also Please don't use keycode as it is deprecated ( link ) and might not work in some cases. 更新:另外,请不要使用键码,因为它已被弃用( link ),在某些情况下可能不起作用。 I've personally faced this issue. 我个人已经遇到了这个问题。 Use which instead. 改用哪个

JSFiddle JSFiddle

$('input').on('keypress', function(){
    $('p').text("worked");
});

var e = jQuery.Event("keypress");
e.which = 13;
$("input").focus().val('test').trigger(e);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM