Simulate 'ENTER' Key Press Like Human Hit On Website [duplicate]

南楼画角 提交于 2019-12-24 04:33:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!