Simulate keypress using jQuery

2019-08-13 02:22发布

I want to simulate an keypress with jQuery.

I already tried this:

$("#canvas").trigger( jQuery.Event( 'keypress', { keyCode: 87, which: 87 }) );

But nothing's happening.

Full code:

$(document).on('keydown', function(e) {

    if(e.keyCode == 49) {

        $("#canvas").trigger( jQuery.Event( 'keypress', { keyCode: 87, which: 87 }) );

    }

});

What am i doing wrong?

2条回答
地球回转人心会变
2楼-- · 2019-08-13 02:34

here is a test it works

var e = $.Event('keypress');
e.which = 87;
$('#canvas').trigger(e);
查看更多
Bombasti
3楼-- · 2019-08-13 02:58

you can try this one:

You can create an Event object

$('#canvas').trigger(jQuery.Event('keypress', {keyCode: 87, which: 13}));

You maybe have to try which parameter to set, e.g. keyCode.

or

The real answer has to include keyCode:

var e = jQuery.Event("keydown");
e.which = 50; // # Some key code value
e.keyCode = 50
$("input").trigger(e);

Even though jQuery's website says that which and keyCode are normalized they are very badly mistaken. It's always safest to do the standard cross-browser checks for e.which and e.keyCode and in this case just define both.

or

jQuery has a .keypress method accepting no arguments that simulates a keypress.

$("#canvas").keypress();

Will trigger a keypress on #canvas

If you'd like to also select which key was pressed, you can use .trigger. This example is from the Docs.

var e = $.Event("keydown", { keyCode: 87}); //"keydown" if that's what you're doing
$("body").trigger(e);

The key code 87 is the Key code backspace in javascript

Let me know how that works for you :)

My demo pages:

DEMO 1

DEMO 2

查看更多
登录 后发表回答