javascript 模拟“ENTER”按键,就像人类在网站上点击一样

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25947040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:17:02  来源:igfitidea点击:

Simulate 'ENTER' Key Press Like Human Hit On Website

javascriptjquerykeyentersimulate

提问by riko10

Is it possible in Javascript/JQuery ?

是否可以在 Javascript/JQuery 中使用?

I have a button on my website and I need to simulate human press key "Enter" when someone clicks the button.

我的网站上有一个按钮,当有人单击该按钮时,我需要模拟人工按键“Enter”。

Example: I clicked button and then it automatically pressed Enter key.

示例:我单击了按钮,然后它自动按下了 Enter 键。

回答by James Gould

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.

您要定义一个按键事件,将其定义为Enter(13) keypress 并触发它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.

编辑新问题:keypress、keydown 和 keyup 事件实际上不输入任何内容,它们仅用于触发事件绑定。如果需要,您还必须添加输入。此行将键码转换回字符串并将其附加到当前值。

$("#test").val($("#test").val()+String.fromCharCode(e.which));

Updated JsFiddle

更新了 JsFiddle

I also included two commented out lines of code that show two ways to submit the form programmatically.

我还包含了两行注释掉的代码,它们显示了以编程方式提交表单的两种方法。

$('#submit').click();

and

$('#myForm').submit();