简体   繁体   English

jQuery Focus()或keypress()在IE和Chrome中不起作用

[英]jQuery Focus() or keypress() not working in IE and Chrome

I have the code blow for tabbing through 2 fields and it has no effect in IE and Chrome, it seems it runs nothing (for example I get nothing when I put alert) and in Firefox it runs with some bug (it jumps twice there) where do you think the problem is, I'm developing in by ASP.Net and jQuery version 1.3.2 我有2个字段的标签代码问题,它在IE和Chrome中没有任何作用,似乎它什么也没运行(例如,当我发出警报时我什么也没得到),而在Firefox中,它却运行了一些错误(在那跳了两次)您认为问题出在哪里,我正在使用ASP.Net和jQuery 1.3.2开发

$(document).ready(function () {
    $("#TextBox1").keypress(function (e) {
        var kCode = e.keyCode || e.charCode; 
        if (kCode == 9) {
            $("#TextBox2").focus();
        }
    });
});

I think the main problem is that you're using the keypress event, which should only be fired when a character is added to the input, not when any key (like TAB) is pressed. 我认为主要问题是您正在使用keypress事件,该事件仅应在将字符添加到输入中时触发,而不是在按下任何键(例如TAB)时才触发。

To handle other key presses you will need to use keydown . 要处理其他按键,您将需要使用keydown However, testing that in your fiddle seems to still not work. 但是,对您的小提琴进行测试似乎仍然无效。 To make it work (in Chrome at least), I had to prevent the default action: 为了使其正常运行(至少在Chrome中),我不得不阻止默认操作:

$(document).ready(function () {
    $("#TextBox1").keydown(function (e) {
        e.preventDefault();
        var kCode = e.keyCode || e.charCode; 
        console.log(kCode);
         if (kCode == 9) {
            $("#TextBox2").focus();
        }
    });
});

Here's an update fiddle . 这是一个更新小提琴 However, if I've understood your question correctly, all you're trying to do is change the focused element when the tab key is pressed... if that's right, why not just use the tabindex attribute instead? 但是,如果我正确地理解了您的问题,那么您要做的就是在按下Tab键时更改焦点元素...如果是的话,为什么不只使用tabindex属性呢?

The keypress event does not fire for tab (keycode 9). 选项卡 (键码9)不会触发keypress事件。 You'll need to use keyup or keydown . 您需要使用keyupkeydown

If this is ASP.NET, you need to reference the controls by the ClientID : 如果是ASP.NET,则需要通过ClientID引用控件:

$(document).ready(function () { 
    $("#<%=TextBox1.ClientID%>").keypress(function (e) { 
        var kCode = e.keyCode || e.charCode;  
         if (kCode == 9) { 
            $("#<%=TextBox2.ClientID%>").focus(); 
        } 
    }); 
}); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM