2017-08-02 31 views
0

jQuery的模糊&聚焦在IE或Chrome差

<html> 
 
<head><title>asdf</title></head> 
 
<body> 
 
<input type="text" id="WTF"> 
 

 
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script> 
 
<script> 
 
    $("#WTF").blur(function() { 
 
     if($("#WTF").val() !== "WTF"){ 
 
      alert("WTF!"); 
 
      $("#WTF").focus(); 
 
     } 
 
    }); 
 
</script> 
 
</body> 
 
</html>

這樣的代碼。 如果在IE中打開,則在下一次激活模糊事件之前,可以正確觸發警報一次。但在Chrome中打開,您可以看到警報無盡的觸發器。 爲什麼?那麼如何讓Chrome正確地激活該事件?

+0

所以在Chrome中,重點仍然在'alert'之後的'input',因此你的'blur'被重複觸發。你的要求是什麼?你想在'輸入'上做什麼? –

+0

Emmm,我想驗證輸入失去焦點時的輸入值。如果不通過,則通過警報提醒輸入錯誤。最後重點關注輸入。 - 像這樣的代碼。 – EmmHaha

+0

我想知道爲什麼IE和Chrome處理這個不同 – EmmHaha

回答

0

所以你提到的事情是在Chrome中已知的bug,你可以閱讀更多關於它here

相反的alert,你可以添加一個錯誤class指示用戶有關錯誤:

.error { 
 
    border: 1px solid #d00; 
 
}
<html> 
 

 
<head> 
 
    <title>asdf</title> 
 
</head> 
 

 
<body> 
 
    <input type="text" id="WTF"> 
 

 
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script> 
 
    <script> 
 
    $("#WTF").blur(function() { 
 
     if ($(this).val() !== "WTF") { 
 
     $(this).addClass('error'); 
 
     } else { 
 
     $(this).removeClass('error'); 
 
     } 
 
    }); 
 
    </script> 
 
</body> 
 

 
</html>