如何用jQuery替换击键? [英] How do I replace a keystroke with jQuery?
问题描述
我需要能够用jQuery替换击键.当按下向右箭头时,我希望改为按下Tab键.到目前为止,我有:
I need to be able to replace a keystroke with jQuery. When the right arrow is pressed, I want the tab key to be pressed instead. So far I have:
<script type="text/javascript" src="jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="jquery.simulate.js"></script>
<script type="text/javascript">
$(function () {
$("select").each( function() {
$(this).keydown(function(event) {
if (event.which == '39') {
$(this).simulate("keydown", { keyCode: 9, ctrlKey: false, shirtKey: false });
$(this).simulate("keypress", { keyCode: 9, ctrlKey: false, shirtKey: false });
$(this).simulate("keyup", { keyCode: 9, ctrlKey: false, shirtKey: false });
return false;
}
});
});
});
</script>
39是向右箭头,而9是制表符按钮.另外,模拟keydown递归调用事件处理程序,这显然是不好的,但是即使没有这一行,这仍然行不通.
39 is the right arrow, and 9 is the tab button. Also, the simulate keydown recursively calls the event handler, which is obviously bad, but even without that line, this still doesn't work.
我正在使用位于(http://code.google.com/p/jqueryjs/source/browse/trunk/plugins/simulate/jquery.simulate.js?r=6063)的jquery.simulate.js,因为我找不到仅用jQuery模拟按键的方法.
I'm using jquery.simulate.js located at (http://code.google.com/p/jqueryjs/source/browse/trunk/plugins/simulate/jquery.simulate.js?r=6063) because I couldn't find a way to simulate a keypress with just jQuery.
按键只是不能模拟实际的按键.
The keypress just doesn't simulate the actual key press.
推荐答案
您无法使用javascript模拟实际的按键.它是浏览器安全性的核心组成部分.想象一下能够模拟Alt-Tab或Ctrl-Shift-Del.
You can't simulate actual keypresses with javascript. It's a core component of browser security. Imagine being able to simulate Alt-Tab, or Ctrl-Shift-Del.
您当然可以定义一个方法来封装要触发的行为,并在按下特定键时调用该方法.
You can, of course, define a method that encapsulates the behavior you want to trigger, and call that method when specific keys are pressed.
例如,当有人在另一个选择元素上按下向右箭头时,要跳至下一个选择元素,我将保留页面上所有选择元素的列表;当按下右箭头时,我将在列表中找到当前焦点选择的位置,并在下一个焦点中找到.focus().
So, for example, to jump to the next select element when someone presses the right arrow while on another select element, I'd keep a list of all the select elements on the page; when the right-arrow is pressed, I'd find the position of the currently-focused select in that list, and .focus() the next one.
这篇关于如何用jQuery替换击键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!