javascript focus()不专注

常规文本字段,用户输入字符串.测试a)输入中是否有东西,b)输入中没有空格,c)只是整数,没有其他字符.
然后是提交按钮.
你会注意到我没有使用html行为,输入中没有onclick,严格的内容/表示/行为分离.

我的HTML

<form name="basicText" id="basicText" action="">
<p>Enter any ol' integer: 
<input type="text" id="inputBox" name="inputBox" size="14"/>    
<input value = "Next...?" type="submit" id="mySubmitBtn" name="mySubmitBtn"/>
</p>
</form>
<script src="js/w1bscript.js" type="text/javascript"></script>

另请注意,外部javascript文件在末尾添加,因此所有元素都可以加载(现在不用担心onload).

JavaScript:

var myButton1 = document.getElementById("mySubmitBtn");
var myForm1 = document.getElementById("basicText");
var myTextBox = myForm1.inputBox;

function submitPress() {
 if(myTextBox.value.length == 0) {
    alert("You didn't enter anything! Once more time,with feeling...")
    basicText.focus();
    basicText.select();
 } else if(/\s/.test(myTextBox.value)) {
    alert("Eh... No spaces. Just integers. Try again...");
    basicText.focus();
    basicText.select();
  } else if (isNaN(myTextBox.value)==true) {
    alert("Eh... Gonna need you to enter ONLY digits this time. kthnx.");
    basicText.focus();
    basicText.select();
 } else {
    // The textBox isn't empty,and there's no spaces. Good.
    alert("you've passed the test!")
  }
}
myButton1.addEventListener('click',submitPress,false);

当我输入错误的输入时,逻辑工作,但无论我使用什么浏览器,光标都不会聚焦回文本框.

小提琴:http://jsfiddle.net/2CNeG/

谢谢,

解决方法

您将观察到,一旦您对警报框进行了评论,您将能够看到您的焦点正在工作.但是有一个解决方案.试试这个.我认为它应该有效.
setTimeout(function() {
      document.getElementById('inputBox').focus();
    },0);

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...