【问题标题】:javascript focus() isn't focusingjavascript focus() 没有聚焦
【发布时间】:2012-04-06 03:23:16
【问题描述】:

常规文本字段,用户输入一个字符串。测试 a) 输入中是否有内容,b) 输入中是否没有空格,以及 c) 是否仅为整数,没有其他字符。 然后是提交按钮。 你会注意到我没有使用 html 行为,输入中没有 onclick,严格的 Content/Presentation/Behavior 分离。

我的 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/

谢谢, 唐

【问题讨论】:

    标签: javascript focus external


    【解决方案1】:

    您会观察到,一旦您评论了警报框,您将能够看到您的焦点在起作用。但是同样有一个解决方案。试试这个。我认为它应该可以工作。

    setTimeout(function() {
          document.getElementById('inputBox').focus();
        }, 0);
    

    【讨论】:

      【解决方案2】:

      在我看来,您正在关注表单元素;你需要专注于你的文本框:

      document.getElementById('inputBox').focus();
      

      myTextBox.focus() 在您的代码中。

      【讨论】:

      • @DonG 无论是否通过验证,您似乎也在提交表单。
      • 是的;对于那些验证失败的路径,他最好使用 type='button' --OR-- 在验证函数中返回 false。
      • 好的,我明白你的意思了,我把它改成了 myTextBox.focus();并且仍然没有关注输入/文本框。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-10
      相关资源
      最近更新 更多