在alert()之后如何给予focus()? [英] How to give focus() after an alert()?

查看:664
本文介绍了在alert()之后如何给予focus()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 < input type =textboxid =partNumberonChange =validatePart这一点);> 
< input type =textboxid =quantityonfocus =saveOldQuantity(this);>

onChange 事件在一个改变是文本框失去焦点。当数量获得关注时, onfocus 事件正确触发以保存数量的旧值

如果 validatePart()检测到无效的 partNumber value,它 alert 是用户的事实。在 alert()已清除之后,我想将焦点返回到 partNumber 输入。但是在输入节点上执行 focus()并没有给予关注。调试在这里很棘手,因为IE调试窗口的交互当然会改变焦点。



如何确保焦点返回到 partNumber 如果在 validatePart()中检测到错误?



编辑:
一个简单版本的 validatePart()

  function validatePart {
if(!node.value){
alert('请输入零件号。
node.focus(); //< =======为什么这没有任何效果?
}
}


解决方案

添加一个小的超时并将重点重定向到 partNumber 文本框应该做的伎俩。



所以你的 validatePart()函数变成如下:

  function validatePart(node){
if(!node.value){
alert('请输入零件号。
setTimeout(function(){node.focus();},1);
}
}

这是一个快速的实时示例,只需触发警报,无论输入到 partNumber 文本框,并成功将焦点返回到 partNumber 文本框(即使您将其标记为数量文本框。


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 alerts 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??
    }
}

解决方案

Adding a small timeout and resetting the focus back to the partNumber textbox should do the trick.

Thus your validatePart() function becomes something like:

function validatePart(node) {
    if (!node.value) {
        alert('Please enter a part number.');
        setTimeout(function(){node.focus();}, 1);
    }
}

Here's a quick "live" example that simply fires an alert no matter what is entered into the partNumber textbox and successfully returns focus back to the partNumber textbox (even if you tab off it to the quantity textbox.

这篇关于在alert()之后如何给予focus()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆