javascript 无限循环中的Javascript警报消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6356341/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:24:09  来源:igfitidea点击:

Javascript alert messages in infinite loop

javascripthtmldom-events

提问by Rohit Sharma

Alert boxes in infinite loop, here I am trying to put a popup alert message on 2 consecutive fields so they cannot be left blank, I know why it is happening - because when onblur event of 1st function is launched it gives focus to second one & when it jumps back to first one onblur of 2nd textfield is launched.

无限循环中的警报框,在这里我试图在 2 个连续的字段上放置一个弹出警报消息,因此它们不能留空,我知道为什么会发生这种情况 - 因为当第一个函数的 onblur 事件启动时,它会将焦点放在第二个和当它跳回到第一个时,第二个文本字段的 onblur 被启动。

I know validation would be best when done at the form level, but this is the requirement I got.

我知道在表单级别进行验证是最好的,但这是我得到的要求。

Any help?

有什么帮助吗?

Javascript code

Javascript代码

function x()
{
   if( document.getElementById("1").value.length==0)
   {
      alert('1 is required');
      document.getElementById("1").focus();
   }
}

function y()
{
   if(document.getElementById("2").value.length==0)
   {
      alert('2 is required');
      document.getElementById("2").focus();
   }
}

HTML code

HTML代码

<input type="text" name="City Name" id="1" onblur="javascript:x();">
<input type="text" name="Kitty Name" id="2" onblur="javascript:y();">

回答by Theopaul Kakkassery

Instead of handling it in onblur()event, you can handle it in onchange()event.

onblur()您可以在事件中处理它,而不是在事件中处理它onchange()

If you still want to use onblur(), then use the focus inside setTimeoutas shown below.

如果还想用onblur(),那就用焦点里面setTimeout,如下图。

alert('2 is required');
setTimeout(function() { document.getElementById("2").focus(); }, 100); 

回答by James Wiseman

There is a fundamental problem when trying to refocus on a field on an onblurwhen it is invalid. If the user decides to navigate away, the simply can't. When they click away from the field, they are forcibly taken back. I have seen instances where a user is forced to kill their browser session, just to escape an over-zealous onblurvalidation.

当试图重新关注一个onblur无效的领域时,存在一个基本问题。如果用户决定离开,那根本就不能。当他们点击离开场地时,他们会被强行收回。我见过用户被迫终止浏览器会话,只是为了逃避过度onblur验证的实例。

I realise this might not be the exact solution you are after, but can I recommend another approach that still involves client-side validation.

我意识到这可能不是您所追求的确切解决方案,但我能否推荐另一种仍然涉及客户端验证的方法。

I recommend you highlight the field as being invalid in some way on the onblur. E.g. put a star next to it, highlight it red, etc. This way you can dispense with the alertand user still has control.

我建议您在onblur. 例如,在它旁边放一颗星,将其突出显示为红色等。这样您就可以省去alert并且用户仍然可以控制。

When the user comes to submit the form, you perform your client-side checks and display alert to them then (see @Phill Sacre's answer)

当用户提交表单时,您执行客户端检查并向他们显示警报(请参阅@Phill Sacre 的回答)

回答by James Wiseman

My suggestion: consolidate your validation into one method, and check each sequentially in it.

我的建议:将您的验证合并为一种方法,并在其中依次检查每个方法。

So (pseudo-code):

所以(伪代码):

function validate() {
     for (field in fieldlist) {
         if (document.getElementById(field).value.length == 0) {
              displayerror();
              document.getElementById(field).focus();
         }
     }
}

This way you will only ever display one error at a time.

这样您一次只会显示一个错误。

回答by Lightness Races in Orbit

My recommendation is to temporarily disable the blurhandler during the execution of the other input's handler.

我的建议是blur在执行其他输入的处理程序期间暂时禁用处理程序。

I've also replaced your HTML onblurwith a proper Javascript solution, removed the blank lines and added code indentation.

我还用onblur适当的 Javascript 解决方案替换了您的 HTML ,删除了空行并添加了代码缩进。

I've also changed the element IDs, which are not allowed to start with numbers; your script would not have worked at all on compliant browsers.

我还更改了元素 ID,不允许以数字开头;您的脚本在兼容的浏览器上根本无法运行。

<html>
<body>

<script type="text/javascript">
window.onload = function() {
   document.getElementById("input1").onblur = x;
   document.getElementById("input2").onblur = y;
};

function x() {
   if (document.getElementById("input1").value.length == 0) {
     alert('1 is required');

     // temporarily disable binding
     document.getElementById("input2").onblur = function() {};

     document.getElementById("input1").focus();

     // re-bind
     document.getElementById("input2").onblur = y;
   }
}

function y() {
   if (document.getElementById("input2").value.length == 0) {
     alert('2 is required');

     // temporarily disable binding
     document.getElementById("input1").onblur = function() {};

     document.getElementById("input2").focus();

     // re-bind
     document.getElementById("input1").onblur = x;
   }
}
</script>

<input type="text" name="City Name" id="input1" onblur="javascript:x();">
<input type="text" name="Kitty Name" id="input2" onblur="javascript:y();">

</body>
</html>

Now, this script is rather verbose and carries a lot of code duplication. But in the interests of staying on-topic, I'll leave further improvements for another day.

现在,这个脚本相当冗长并且带有大量的代码重复。但为了保持主题,我将留待另一天进一步改进。

I would also suggest not doing this at all; as James said, it's irritating.

我还建议根本不要这样做;正如詹姆斯所说,这令人恼火

回答by Ahmed Magdy

My be you have to change your way of comparison from

我是你必须改变你的比较方式

document.getElementById("1").value.length==0

to

document.getElementById("1").value != ''

it seems to me that length is always not equal zero

在我看来,长度总是不相等的 zero

回答by Maddy

Try this

试试这个

<html>
    <head>
    <script>

function x() {
   if (document.getElementById("input1").value.length == 0 ) {
     alert('1 is required');
     document.getElementById("input1").focus();

   }
   else  if (document.getElementById("input2").value.length == 0 ) {
     alert('2 is required');
     document.getElementById("input2").focus(); 
   }

}

</script>
    </head>
    <body >
    cityname:
    <input type="text" name="City Name" id="input1" onblur="javascript:x();">
    <br/>
    KittyName:
<input type="text" name="Kitty Name" id="input2" onblur="javascript:x();">

    </body>
</html>

回答by Alex Such

Here is my solution:

这是我的解决方案:

function x()
{
   if( document.getElementById("1").value.length==0)
   {
      alert('1 is required');
      document.getElementById("1").focus();
      return false;
   }
   return true
}

function y()
{
   if(x() && document.getElementById("2").value.length==0)
   {
      alert('2 is required');
      document.getElementById("2").focus();
   }
}

So, if 1 is required, the yfunction won't be evaluated

因此,如果需要 1,y则不会评估该函数

回答by Mr.J

If you modify your code like this. It can be solved.

如果你像这样修改你的代码。可以解决。

<html>
<head>
<title>break alert infinite loop </title>
<script>
var e = function( _id ){
    return document.getElementById(_id);
};
window.onload = function(){
    e("test").onblur = function(){
        if( e("test").value != "11" ){
            Msg("Number[11] is only allow");
            e("test").focus();
        }
    };
};

/* fix start */
var beforeMsg = "";
/* fix end */

function Msg( msg ){
    /* fix start */
    if( msg == beforeMsg ){
        return;
    }
    beforeMsg = msg;
    /* fix end */

    alert(msg);

    /* fix start */
    setTimeout(function(){
        beforeMsg = "";
    },1000);
    /* fix end */
}

</script>
</head>
<body>
    <p>only 11 is allow</p>
    <input type="text" id="test"/>
</body>
</html>

回答by Mr.J

other code

其他代码

common.js

常见的.js

if( window.COMMON_JS == undefined ){
    window.COMMON_JS = "common.js ver:1.0.0.1";

    window.AletMessage = "";
    MessageAlert = function( msg ){
        if( window.AletMessage == msg  ){
            return;
        }
        window.AletMessage = msg;
        alert(msg);
        setTimeout(function(){
            window.AletMessage = "";    
        },1000);
    };
}

test.html

测试.html

<html>
<head>
<script type="text/javascript" src="common.js"></script>
<script>
var e = function( _id ){
    return document.getElementById(_id);
};
window.onload = function(){
    e("test").onblur = function(){
        if( e("test").value != "11" ){
            MessageAlert("Number[11] is only allow");
            e("test").focus();
        }
    };
};
</script>
</head>
<body>
    <p>Only 11 allowed.</p>
    <input type="text" id="test"/>
</body>
</html>

回答by Nivrutti Patil

I have one JS and have one function which is called onblurevent of textbox and onblurthat event is in Infinite loop.

我有一个 JS 并有一个函数,称为onblur文本框事件,onblur该事件处于无限循环中。

After that, I have declared one global variable (On the top of JS and outside the function Var Isvalid = true;)

之后,我声明了一个全局变量(在 JS 顶部和函数外Var Isvalid = true;

In function, Performing validation code.

在功能上,执行验证代码。

if (IsValid == true)
{   
    if validation is false.
    giving alert message.
    and updating the IsValid = false;
}

If the validation is true then updating the global variable. Isvalid = true;

如果验证为真,则更新全局变量。 Isvalid = true;

In second recursion it will not execute the loop. If in next phase if blur event occurred then variable automatically set to True.

在第二次递归中,它不会执行循环。如果在下一阶段,如果发生模糊事件,则变量自动设置为True