[英]Chrome: Blur - Alert - Focus sequence causes infinite alert loop
Consider this code: 考虑以下代码:
var input = document.getElementById("hello"); input.addEventListener('blur', function() { alert('hello'); input.select(); input.focus(); });
<input type="text" value="hello" id="hello" />
The idea around it is to keep the user focused in the input until he/she enters a valid text in it. 围绕它的想法是让用户专注于输入,直到他/她输入有效文本。 This is a simplified version of the code.
这是代码的简化版本。
Js fiddle here: https://jsfiddle.net/wzwft49w/9/ Js在这里小提琴: https : //jsfiddle.net/wzwft49w/9/
Problem: If you focus on the input and then blur it, you will get an infinite alert popup in Chrome but not in IE. 问题:如果您专注于输入然后模糊它,您将在Chrome中获得无限警报弹出窗口,但不会在IE中获得。
1. How would you solve this problem? 你怎么解决这个问题?
2. Any ideas on why does this happen? 2.为什么会发生这种情况的任何想法?
Notes: 笔记:
Here is my solution for chrome: 这是我的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>
it work for IE too, but this not for Firefox due to focus() is not working correctly. 它也适用于IE,但这不适用于Firefox,因为focus()无法正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.