考虑这段代码:
var input = document.getElementById("hello");
input.addEventListener('blur', function() {
alert('hello');
input.select();
input.focus();
});<input type="text" value="hello" id="hello" />
围绕它的想法是让用户专注于输入,直到他/她在其中输入有效文本。这是代码的简化版本。
Js fiddle 在这里:https://jsfiddle.net/wzwft49w/9/
问题:如果您将注意力集中在输入上然后对其进行模糊处理,您将在 Chrome 中看到一个无限警告弹出窗口,但在 IE 中则不会。
1。你会如何解决这个问题?
2。关于为什么会发生这种情况的任何想法?
注意事项:
最佳答案
这是我的 chrome 解决方案:
var inputs = document.querySelectorAll("input"),
len = inputs.length,
i;
var gflag=false;
function myalert(m,o) {
if (gflag) {
return;
}
gflag=true;
alert(m);
o.focus();
setTimeout(function() {gflag=false;},10);
}
function makeBlurHandler() {
"use strict";
return function () {
if (this.value === "") {
myalert("Cannot be blank!",this);
this.nextElementSibling.innerHTML = "Cannot be blank!";
} else {
this.nextElementSibling.innerHTML = "";
}
};
}
for (i = 0; i < len; i++) {
inputs[i].addEventListener("blur", makeBlurHandler());
}.errorMessage {
color: red;
}<p>
<label for="userName">User Name:</label>
<input type="text" id="userName">
<span class="errorMessage"></span>
</p>
<p>
<label for="passWord">Password:</label>
<input type="text" id="passWord">
<span class="errorMessage"></span>
</p>
它也适用于 IE,但由于 focus() 无法正常工作,因此不适用于 Firefox。
关于javascript - Chrome : Blur - Alert - Focus sequence causes infinite alert loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41603134/