jQuery 焦点在 Chrome 中不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17384464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery focus not working in Chrome
提问by rybo111
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?
有谁知道我该如何解决这个问题?
回答by claustrofob
Seems like a bug in Chrome. Sometimes it is too fast to execute events properly;)
似乎是 Chrome 中的一个错误。有时正确执行事件太快了;)
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. It will slow down Chrome and make it work.
使用setTimeout
具有最小的延迟。它会减慢 Chrome 的运行速度并使其正常工作。
回答by A. Wolff
You should use:
你应该使用:
$("#one").on("keyup paste",function() {
console.log($(this).val());
if($(this).val().length == 2) { $("#two").focus(); }
});
And the same for the #five
handler.
而同样的#five
处理程序。
The oninput
event seems to have the same behaviour as onkeypress
.
该oninput
事件似乎与onkeypress
.
回答by Sahin Yanl?k
$("#one").keydown(function(){
if($(this).val().length==2)
{
$("#two").focus();
}
});
回答by Seema Gopinath
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.
希望这可以帮助那些没有使用其他建议使其工作的人。