简体   繁体   English

jQuery 焦点在 Chrome 中不起作用

[英]jQuery focus not working in Chrome

Please see this fiddle: http://jsfiddle.net/yg49k/请看这个小提琴: http://jsfiddle.net/yg49k/

The following code works fine in FireFox but doesn't work in the latest version of Chrome.以下代码在 FireFox 中运行良好,但在最新版本的 Chrome 中不起作用。

HTML: HTML:

<input type="text" id="one" placeholder="Type two chars" />
<input type="text" id="two" placeholder="It should focus here" />

jQuery: jQuery:

$("#one").on("input", function() {
    if($("#one").val().length == 2) { $("#two").focus(); }
});

Does anyone know how I can get around this?有谁知道我该如何解决这个问题?

Seems like a bug in Chrome. 好像是Chrome中的一个错误。 Sometimes it is too fast to execute events properly;) 有时候执行事件太快了;)

Found a workaround http://jsfiddle.net/Rd2rZ/ 找到了解决方法http://jsfiddle.net/Rd2rZ/

$("#one").on("input", function() {
    if($("#one").val().length == 2) { 
        setTimeout(function(){
            $("#two").focus();
        }, 1);
    }
});

Use setTimeout with a minimal delay. 使用setTimeout具有最小延迟。 It will slow down Chrome and make it work. 它会降低Chrome的速度并使其正常运行。

You should use: 你应该使用:

$("#one").on("keyup paste",function() {
    console.log($(this).val());
    if($(this).val().length == 2) { $("#two").focus(); }
});

DEMO DEMO

And the same for the #five handler. #five处理程序也一样。

The oninput event seems to have the same behaviour as onkeypress . oninput事件似乎与onkeypress具有相同的行为。

$("#one").keydown(function(){
   if($(this).val().length==2)
   {
      $("#two").focus();
   }
});

 $("#one").on("input", function() { if($("#one").val().length == 2) { $("#two")[0].focus(); } });

Try this!试试这个!

I got the same problem and got it fixed using the following code: 我遇到了同样的问题,并使用以下代码修复了它:
You should also have a name attribute for your input to get this working. 您还应该为输入设置name属性以使其正常工作。

$("#one").on("input", null, null, function() {  
   if($("#one").val().length == 2) {  
       setTimeout(function() { $('input[name="one"]').focus() }, 3000);  
   }  
});  

Hope this helps someone who did not get it working using the other suggestions. 希望这可以帮助那些没有使用其他建议的人。

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

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