在下面的代码中,我想设置 var hasFocus=False;
在提到的 <textarea>
模糊 500 毫秒后和 <input>
.此代码立即变为 hasFocus=False
第一次无需等待 500 毫秒。之后,它按预期工作。
我无法理解为什么它第一次没有按预期运行!
$(function(){
var hasFocus=false;
$("textarea[name='question1'], input[name^=q1_option]").blur(function(event){
setTimeout(function(){
hasFocus=false;
},500);
}).focus(function(){
hasFocus=true;
});
$(document).on('click',function(e){
console.log("focus :" +hasFocus);
if(hasFocus)
{
alert("Working!!"); //Now this does not come up for the first time!
}
})
});
最佳答案
那是因为您的 console.log
在触发超时模糊事件之前执行,因此控制台显示之前的值。将 console.log("focus :"+hasFocus);
移动到您的 blur
和 focus
函数中,以查看一切正常。
演示 - Fiddle
关于javascript - setTimeout 仅在导致它的事件的第一次不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35145309/