How do I replace a keystroke with jQuery?

心不动则不痛 提交于 2019-12-02 04:19:15

问题


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 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.

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.


回答1:


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.

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.



来源:https://stackoverflow.com/questions/6064707/how-do-i-replace-a-keystroke-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!