模拟"ENTER"按键,就像在网站上被人击中一样

问题描述:

在Javascript/JQuery中可以吗?

Is it possible in Javascript/JQuery ?

我的网站上有一个按钮,当有人单击该按钮时,我需要模拟人类按"Enter"键.

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.

我从此答案

var onclick = function(){
    var e = $.Event('keypress');
    e.which = 13; // Character 'A'
    $(this).trigger(e);
};

$('button').click(onclick);

您要定义一个按键事件,将其定义为 Enter (13)按键,然后触发它onclick.

You want to define a keypress event, define it as the Enter (13) keypress, and trigger it onclick.

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

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));

更新了JsFiddle

我还添加了两行注释掉的代码行,这些行显示了以编程方式提交表单的两种方式.

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

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

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