jQuery 焦点不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18383747/
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
提问by Puzzled Boy
I am trying to focus on credit card validation fail. but strange focus()
not working.
我试图专注于信用卡验证失败。但奇怪的是focus()
不起作用。
$('#cc_number').validateCreditCard(function (result) {
if (result.length_valid && result.luhn_valid) {
} else {
$("#cc_number").focus();
return false;
}
});
<input type="text" id='cc_number' name="cc_number" />
回答by Curt
As mentioned in the comments, your original jsfiddle contains the solution.
如评论中所述,您的原始 jsfiddle 包含解决方案。
A workaround is to put a timeout on the focus call.
解决方法是在焦点调用上设置超时。
setTimeout(function(){
$("#cc_number").focus();
}, 0);
I'm not 100% sure, but it could be that as the alert is called on blur, you're never actually allowing the textbox to lose focus, and therefore when focus is called, it already has it.
我不是 100% 确定,但可能是因为在模糊时调用警报,您实际上从未允许文本框失去焦点,因此当调用焦点时,它已经拥有它。
By using a timeout, you are putting the logic into a seperate thread, which runs seperate to the main javascript code (much like a callback function).
通过使用超时,您将逻辑放入一个单独的线程中,该线程与主 javascript 代码分开运行(很像回调函数)。
But as your question comments also mention, forcing focus until validation passes is annoying.
但是正如您的问题评论也提到的,在验证通过之前强制聚焦很烦人。
But this is more of a UX criticism.
但这更多是对用户体验的批评。
回答by Shoaib Chikate
Your DOM may be getting refresh so focus is not working here. Instead you can follow this approach:
您的 DOM 可能正在刷新,因此焦点在这里不起作用。相反,您可以遵循以下方法:
$('#cc_number').validateCreditCard(function (result) {
if (result.length_valid && result.luhn_valid) {
} else {
$("#cc_number").attr("autofocus","autofocus")
return false;
}
});