問題描述
使用 jQuery,如何在單擊鏈接時模擬(觸發?) KeyPress?例如,當用戶點擊以下鏈接時:
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>
然后,通過單擊鏈接,就好像他們按下了鍵盤上的空格鍵".
Then, by clicking the link, it would be as if they pressed the "spacebar" on their keyboard.
我假設是這樣的:
$("#clickforspace").click(function(e) {
e.preventDefault();
//... Some type of code here to initiate "spacebar" //
});
關于如何實現這一點的任何想法?
Any ideas on how to achieve this?
推薦答案
來自 jQuery 的 keypress 事件旨在完成此類工作.您可以通過將字符串keypress"傳遞給 .trigger() 來觸發事件.然而,更具體地說,您實際上也可以傳遞一個 jQuery.Event 對象(將類型指定為keypress")并提供您想要的任何屬性,例如作為空格鍵的鍵碼.
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
閱讀以上文檔了解更多詳情.
Read the above documentation for more details.
這篇關于用 jQuery 模擬按鍵的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!