问题
Is it possible in Javascript/JQuery ?
I have a button on my website and I need to simulate human press key "Enter" when someone clicks the button.
Example: I clicked button and then it automatically pressed Enter key.
回答1:
I modified this code from the code in this answer,
var onclick = function(){
var e = $.Event('keypress');
e.which = 13; // Character 'A'
$(this).trigger(e);
};
$('button').click(onclick);
You want to define a keypress event, define it as the Enter (13) keypress, and trigger it onclick
.
Edit for new question: The keypress, keydown, and keyup events don't actually input anything, they're solely for triggering event bindings. You must also add the input if you want that as well. This line translates the keycode back to a string and appends it to the current value.
$("#test").val($("#test").val()+String.fromCharCode(e.which));
Updated JsFiddle
I also included two commented out lines of code that show two ways to submit the form programmatically.
$('#submit').click();
and
$('#myForm').submit();
来源:https://stackoverflow.com/questions/25947040/simulate-enter-key-press-like-human-hit-on-website