简体   繁体   English

无限循环中的Javascript警报消息

[英]Javascript alert messages in infinite loop

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

Instead of handling it in onblur() event, you can handle it in onchange() event. 您可以在onchange()事件中处理它,而不是在onblur()事件中处理它。

If you still want to use onblur() , then use the focus inside setTimeout as shown below. 如果你仍然想使用onblur() ,那么使用setTimeout的焦点,如下所示。

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

There is a fundamental problem when trying to refocus on a field on an onblur when it is invalid. 当无效时,尝试重新聚焦onblur上的字段时存在一个基本问题。 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 onblur validation. 我已经看到用户被迫杀死他们的浏览器会话的实例,只是为了逃避过度热心的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 . 我建议您在onblur上以某种方式突出显示该字段无效。 Eg put a star next to it, highlight it red, etc. This way you can dispense with the alert and user still has control. 例如,在它旁边放一颗星,突出显示为红色等。这样您就可以省去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的回答)

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. 这样,您一次只能显示一个错误。

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>

other code 其他代码

common.js common.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 的test.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>

I have one JS and have one function which is called onblur event of textbox and onblur that 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. 如果验证为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

Try Below Js Code. 尝试下面的Js代码。 It will solve your problem. 它会解决你的问题。

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


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

With the use of timeouts you can disable the onBlur event on the "target" element and go back to the source element. 通过使用超时,您可以在“target”元素上禁用onBlur事件并返回源元素。 This works in IE. 这适用于IE。

function focusWithoutEvents(object) {
    // Small timeout so that the active element will be the "next" element
    setTimeout(function() {
        var activeElement = document.activeElement;

        // Save the current onblur()
        var activeOnblur = activeElement.onblur;

        // Disable the onblur event
        activeElement.onblur = null;

        // Now we can focus without triggering onblur event
        object.focus();

        // With a small delay, put back the onblur code.
        setTimeout(function() {
            activeElement.onblur = activeOnblur
        }, 100);
    }, 100);
}

My recommendation is to temporarily disable the blur handler during the execution of the other input's handler. 我的建议是在执行其他输入的处理程序期间暂时禁用blur处理程序。

I've also replaced your HTML onblur with a proper Javascript solution, removed the blank lines and added code indentation. 我还用适当的Javascript解决方案替换了你的HTML onblur ,删除了空白行并添加了代码缩进。

I've also changed the element IDs, which are not allowed to start with numbers; 我还更改了元素ID,不允许以数字开头; your script would not have worked at all on compliant browsers. 您的脚本在兼容的浏览器上根本不起作用。

<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 . 正如詹姆斯所说,这令人生气

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

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>

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 y function won't be evaluated 因此,如果需要1,则不会评估y函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM