Using jQuery, how can I simulate (trigger?) a KeyPress when a link is clicked? For example, when a user clicks the following link:

<a id="clickforspace" href="#">Click Here</a>

然后,通过点击链接,就好像他们按下了键盘上的"空格键".

我猜想大概是这样的:

$("#clickforspace").click(function(e) { 
    e.preventDefault(); 
    //... Some type of code here to initiate "spacebar" //
                                      });

Any ideas on how to achieve this?

推荐答案

The keypress event from jQuery is meant to do this sort of work. You can trigger the event by passing a string "keypress" to .trigger(). However to be more specific you can actually pass a jQuery.Event object (specify the type as "keypress") as well and provide any properties you want such as the keycode being the spacebar.

http://docs.jquery.com/Events/trigger#eventdata

阅读以上文档了解更多详细信息.

Jquery相关问答推荐

提交表单时运行自定义验证脚本

如何使用 JQuery 将详细信息中的项目包装在容器中?

Jquery each - 停止循环并返回对象

ajax调用后Jquery事件不会触发

如何在 jQuery 中 Select 特定的表单元素?

jQuery javascript 正则表达式 将
替换为 \n

使用 bootstrap-datepicker 检测对选定日期的更改

如何立即启动 setInterval 循环?

使用 jQuery 从 JavaScript 对象中添加/删除项目

使用 jQuery 刷新(重新加载)页面一次?

动画元素变换旋转

为什么 Chrome 会忽略本地 jQuery cookie?

获取跨域 iframe 的 DOM 内容

jQuery UI 中的 disableSelection 用于什么?

如何将数组传递给 jQuery .data() 属性

父母的jQuery父母

jQuery vs jQuery Mobile vs jQuery UI?

如何在 JavaScript / jQuery 中获取对象的属性?

使用javascript将HTML页面中的div下载为pdf

如何使用 jQuery Select 第一个父 DIV?