如何在alert()之后给予focus()?
我有这样的事情:
<input type="textbox" id="partNumber" onChange="validatePart(this);">
<input type="textbox" id="quantity" onfocus="saveOldQuantity(this);">
onChange
事件在进行更改后正确触发并且文本框失去焦点。当 quantity
获得焦点时,onfocus
事件会正确触发,以在进行更改之前保存 quantity
的旧值。
如果 validatePart()
检测到无效的 partNumber
值,它会提醒
用户该事实。清除 alert()
后,我想将焦点返回到 partNumber
输入。但是在输入节点上执行 focus()
并没有给它焦点。这里的调试很棘手,因为 IE 调试窗口交互当然是改变焦点。
如果在 validatePart()
中检测到错误,如何确保焦点返回到 partNumber
?
编辑: validatePart()
的简单版本:
function validatePart(node) {
if (!node.value) {
alert('Please enter a part number.');
node.focus(); // <======= why isn't this having any effect??
}
}
I have something like:
<input type="textbox" id="partNumber" onChange="validatePart(this);">
<input type="textbox" id="quantity" onfocus="saveOldQuantity(this);">
The onChange
event is properly firing after a change is made and the textbox loses focus. When quantity
gains focus, the onfocus
event is properly firing to save the old value of quantity
before changes are made.
If validatePart()
detects an invalid partNumber
value, it alert
s the user to that fact. After the alert()
has cleared, I'd like to return focus to the partNumber
input. But doing a focus()
on the input node is not giving it focus. Debugging is tricky here, because the IE debug window interaction is, of course, changing the focus.
How can I ensure focus returns to partNumber
if an error is detected in validatePart()
?
EDIT:
A simple version of validatePart()
:
function validatePart(node) {
if (!node.value) {
alert('Please enter a part number.');
node.focus(); // <======= why isn't this having any effect??
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
添加一个小的超时并将焦点重置回
partNumber
文本框应该可以解决问题。因此,您的
validatePart()
函数变得类似于:这是一个快速的“实时”示例无论在
partNumber
文本框中输入什么内容,都会简单地触发alert
并成功地将焦点返回到partNumber
文本框(即使您将其关闭)到数量
文本框。Adding a small timeout and resetting the focus back to the
partNumber
textbox should do the trick.Thus your
validatePart()
function becomes something like:Here's a quick "live" example that simply fires an
alert
no matter what is entered into thepartNumber
textbox and successfully returns focus back to thepartNumber
textbox (even if you tab off it to thequantity
textbox.您的代码似乎按我的预期工作。请参阅此fiddle。您还看到其他行为吗?我看到我在 textbox1 中输入了一个数字。然后,当我切换到 textbox2 时,出现
Invalid Part!
错误,并且焦点保留在当前文本框上。更新 - 由于这似乎只在 Chrome 中运行良好,因此您可以跟踪是否存在错误。如果是的话那就处理一下。
Your code seems to work as expected for me. See this fiddle. Are you seeing some other behavior? I see that I type a number in textbox1. Then when I tab over to textbox2 I get
Invalid Part!
error and focus stays on current textbox.Updated - Since this only seems to play nice in Chrome you could keep track of whether an error exists. If so then handle it.