gpt4 book ai didi

javascript focus() 没有聚焦

转载 作者:数据小太阳 更新时间:2023-10-29 05:04:35 25 4
gpt4 key购买 nike

常规文本字段,用户输入一个字符串。测试 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 文件添加在末尾,因此所有元素都可以加载(现在不用担心加载)。

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);

当我输入不正确的输入时,逻辑正常,但无论我使用什么浏览器,光标都不会聚焦回文本框。

fiddle :http://jsfiddle.net/2CNeG/

谢谢,唐

最佳答案

您会发现,一旦您对警告框进行了评论,您将能够看到您的焦点正在发挥作用。但同样有一个解决方案。一定要试试这个。我认为它应该有效。

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

关于javascript focus() 没有聚焦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10038765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com