使用jQuery触发器无法正确触发keydown事件 [英] keydown event does not fire correctly using jQuery trigger

查看:176
本文介绍了使用jQuery触发器无法正确触发keydown事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

<input name="TextBox1" type="text" value="1111111111" id="TextBox1" />
<br />
<input name="TextBox2" type="text" value="222222222" id="TextBox2" />
<br />
<input name="TextBox3" type="text" value="3333333333" id="TextBox3" />
<br />
<input name="TextBox4" type="text" value="4444444444" id="TextBox4" />
<br />
<select name="DropDownList1" id="DropDownList1">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>
<br />
<input id="CheckBox1" type="checkbox" name="CheckBox1" />
<label for="CheckBox1">nima</label>
<br />
<input id="Button1" type="button" value="button" />

和javascript:

and javascript:

$(document).ready(function () {
        $("#Button1").click(function () {
            var e = jQuery.Event("keydown");
            e.which = 9; // # Some key code value
            e.keyCode = 9;
            $("#TextBox1").trigger(e);
        });

        $("#TextBox1").on("keydown", function (e) {
            alert(e.keyCode);
        });
    });

问题是,当我在TextBox1上按 TAB 时,得到keyCodeTextbox2焦点的消息"9".但是当我按下Button1时,我得到keyCode的消息"9",但是Textbox2没有得到焦点.我的错误在哪里? 谢谢

the problem is when I press TAB on TextBox1 I get message "9" for keyCode and Textbox2 get focus. but when I press Button1 I get message "9" for keyCode but Textbox2 does not get focus. Where is my mistake? thanks

实时演示

推荐答案

错误是您实际上并没有按自己的意愿来处理 TAB ,浏览器是.在一个交互式元素具有焦点的同时按 TAB 会通知浏览器您希望将焦点移至行中的下一个元素(基于tabIndex).

The mistake is that you're not actually handling the TAB press yourself, the browser is. Pressing TAB whilst one interactive element has focus will inform the browser that you wish to have focus moved on to the next element in line (based on tabIndex).

您此处的按钮实际上并没有按下 TAB 键,而是将tab事件传递给了input元素.

Your button here isn't actually pressing the TAB key, it's passing the tab event to the input element.

如果希望此操作使#TextBox1元素模糊并集中#TextBox2元素,则可以使用jQuery的blur()focus()函数:

If you wish to have this action blur the #TextBox1 element and focus the #TextBox2 element, you can make use of jQuery's blur() and focus() functions:

$("#TextBox1").on("keydown", function (e) {
    if (e.which === 9) {
        $(this).blur();
        $('#TextBox2').focus();
    }
});

JSFiddle演示 .

这篇关于使用jQuery触发器无法正确触发keydown事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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