模拟"ENTER"按键,就像在网站上被人击中一样 [英] Simulate 'ENTER' Key Press Like Human Hit On Website

查看:98
本文介绍了模拟"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();

这篇关于模拟"ENTER"按键,就像在网站上被人击中一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆