问题
I am trying to mimic key press events, for instance Ctrl+D on a button click.
It would be great if someone can point me in the right direction on how to achieve the same.
回答1:
You're not allowed to do that. Imagine all the havoc I could wreak if I could send CTRL-ALT-DEL at will.
回答2:
The code for triggering a custom event (in this instance, Ctrl+d) is as follows:
var evt = jQuery.Event("keypress");
evt.keyCode = 100; // d
evt.ctrlKey = true;
$(document).trigger(evt);
NB that, as the other answers have said, this will be limited in its impact. You won't be able to affect normal browser functions in this way.
回答3:
That would be "firing events", though I'm leaving the exercise to you to find the right code.
As the other guy said, you cannot do any kind of thing with it. It is purposefully limited.
However, let's say I have a wysiwyg editor in javascript, which supports receiving ctrl+s and saving, you should be able to fire that yourself and make it save anyway.
At the end, it's a matter of context (focus), and which sometimes fails (again, purposefully).
来源:https://stackoverflow.com/questions/3894617/execute-ctrld-on-button-click