javascript focus() 不聚焦
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10038765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript focus() isn't focusing
提问by DonG
Regular text field, user enters a string. Test whether a) there's something in the input, b) that there's no whitespace in the input, and c)is integers only, no other characters. Then the submit button. You'll note that I'm not using html behavior, there's no onclick in the input, strict Content/Presentation/Behavior separation.
常规文本字段,用户输入一个字符串。测试 a) 输入中是否有内容,b) 输入中是否有空格,以及 c) 是否仅为整数,没有其他字符。然后提交按钮。您会注意到我没有使用 html 行为,输入中没有 onclick,严格的 Content/Presentation/Behavior 分离。
My HTML:
我的 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>
Note also that the external javascript file is added at the end of the so all elements can load (not worrying about onload right now).
另请注意,外部 javascript 文件添加在末尾,因此所有元素都可以加载(现在不必担心 onload)。
The JavaScript:
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);
When I enter an incorrect input, the logic works, but the cursor isn't focusing back to the text box, no matter what browser I use.
当我输入不正确的输入时,逻辑有效,但无论我使用什么浏览器,光标都不会聚焦回文本框。
Fiddle: http://jsfiddle.net/2CNeG/
小提琴:http: //jsfiddle.net/2CNeG/
Thank you, Don
谢谢你,唐
回答by sTg
You will observe that once you have commented your alert box you will be able to see your focus working.But there is a solution for the same. Do try this one.I think it should work.
你会发现,一旦你评论了你的警告框,你就可以看到你的焦点在工作。但是有一个解决方案。一定要试试这个。我认为它应该有效。
setTimeout(function() {
document.getElementById('inputBox').focus();
}, 0);
回答by Authman Apatira
It looks to me like you are focusing on your form element; you need to focus on your text boxes instead:
在我看来,您似乎专注于表单元素;你需要专注于你的文本框:
document.getElementById('inputBox').focus();
or myTextBox.focus()
in your code.
或myTextBox.focus()
在您的代码中。