简体   繁体   English

Javascript:如何遍历元素并为某些元素调用onblur处理程序

[英]Javascript: How to loop through elements and call onblur handler for certain elements

I have a case where I have a bunch of text boxes and radio buttons on a screen all built dynamically with various DIVs. 我遇到的情况是,屏幕上有一堆文本框和单选按钮,它们都是用各种DIV动态构建的。 There are onblur routines for all of the text boxes to validate entry, but depending on the radio button selection, the text box entry could be invalid when it was valid originally. 对于所有文本框,都有onblur例程可以验证输入,但是根据单选按钮的选择,文本框输入在最初有效时可能无效。 I can't use onblur with the radio buttons because they could go from the radio button into one of the text boxes that was made invalid and create an infinite loop since I'm putting focus into the invalid element. 我不能将onblur与单选按钮一起使用,因为它们可能会从单选按钮进入无效的文本框之一,并且由于我将焦点放在无效元素上而创建了无限循环。 Since each text box has its own special parameters for the onblur calls, I figure the best way to do this is to call the onblur event for the textboxes when the form gets submitted to make sure all entry is still valid with the radio button configuration they have selected. 由于每个文本框都有自己的onblur调用专用参数,因此,我认为最好的方法是在提交表单时为文本框调用onblur事件,以确保所有输入对它们的单选按钮配置仍然有效选择了。 I also need it to stop submitting if one of the onblur events returns false so they can correct the textbox that is wrong. 如果onblur事件之一返回false,我也需要它停止提交,以便它们可以更正错误的文本框。 This is what I've written... 这是我写的

    for (var intElement = 0; intElement < document.forms[0].elements.length; intElement = intElement + 1)
    {
        if (document.forms[0].elements[intElement].name.substr(3) == "FactorAmount") // The first 3 characters of the name are a unique identifier for each field
        {
            if (document.forms[0].elements[intElement].onblur())
            {
                return false;
                break;
            }
        }
    }

return true;

I originally had (!document.forms[0].elements[intElement].onblur()) but the alert messages from the onblur events weren't popping up when I had that. 我最初有(!document.forms [0] .elements [intElement] .onblur()),但是从onblur事件获得的警报消息并没有弹出。 Now the alert messages are popping up, but it's still continuing to loop through elements if it hits an error. 现在,警报消息正在弹出,但是如果遇到错误,它仍然继续在元素之间循环。 I've stepped through this with a debugger both ways, and it appears to be looping just fine, but it's either 1) not stopping and returning false when I need it to or 2) not executing my alert messages to tell the user what the error was. 我已经使用调试器完成了这两种方法,似乎循环很好,但是要么是1)没有停止并在需要时返回false,要么是2)没有执行警报消息告诉用户什么错误是。 Can someone possibly help? 有人可以帮忙吗? It's probably something stupid I'm doing. 我在做这件事可能很愚蠢。

The onblur method that is getting called looks like this... 正在被调用的onblur方法看起来像这样...

function f_VerifyRange(tagFactor, reaMin, reaMax, intPrecision, sLOB, sIL, sFactorCode)
{
    var tagCreditOrDebit;
    var tagIsTotal;
    var tagPercentageOrDecimal;

    eval("tagCreditOrDebit = document.forms[0]." + tagFactor.name.substr(0,3) + "CreditOrDebitC");

    eval("tagIsTotal = document.forms[0]." + tagFactor.name.substr(0,3) + "IsTotal");
    eval("tagPercentageOrDecimal = document.forms[0]." + tagFactor.name.substr(0,3) + "PercentageOrDecimal");

    if (tagPercentageOrDecimal.value == "P")
    {
        reaMax = Math.round((reaMax - 1) * 100);
        reaMin = Math.round((1 - reaMin) * 100);

        if (parseFloat(tagFactor.value) == 0)
        {
            alert("Please enter a value other than 0 or leave this field blank.");

            f_SetFocus(tagFactor);
            return false;
        }

        if (tagIsTotal.value == "True")
        {
            if (tagCreditOrDebit.checked)
            {
                if (parseFloat(tagFactor.value) > reaMin)
                {
                    alert("Please enter a value less than or equal to " + reaMin + "% for a credit or " + reaMax + "% for a debit.");
                    f_SetFocus(tagFactor);
                    return false;
                }
            }
            else
            {
                if (parseFloat(tagFactor.value) > reaMax)
                {
                    alert("Please enter a value less than or equal to " + reaMin + "% for a credit or " + reaMax + "% for a debit.");
                    f_SetFocus(tagFactor);
                    return false;
                }
            }
        }
    }

    return true;
}

EDIT: I think I've figured out why this isn't working as expected, but I still don't know how I can accomplish what I need to. 编辑:我想我已经弄清楚了为什么这没有按预期工作,但是我仍然不知道如何才能完成我需要的工作。 The line below... 下面的行...

            if (!document.forms[0].elements[intElement].onblur())

or 要么

            if (document.forms[0].elements[intElement].onblur())

is not returning what the single onblur function (f_VerifyRange) is returning. 不返回单个onblur函数(f_VerifyRange)返回的内容。 Instead it is always returning either true or false no matter what. 相反,无论如何,它总是返回true或false。 In the first case, it returns true and then quits and aborts the submit after the first textbox even though there was no error with the first textbox. 在第一种情况下,即使第一个文本框没有错误,它也会返回true,然后退出并中止第一个文本框之后的提交。 In the second case, it returns false and runs through all the boxes. 在第二种情况下,它返回false并遍历所有框。 Even though there might have been errors (which it displays), it doesn't think there are any errors, so it continues on with the submit. 即使可能有错误(它显示),它也不认为有任何错误,因此继续进行提交。 I guess what I really need is how to get the return value from f_VerifyRange which is my onblur function. 我想我真正需要的是如何从f_VerifyRange获取返回值,这是我的onblur函数。

This question is a bit too involved for me at this time of the night, but I will give you this bit of advice: 在夜晚的这个时间,这个问题对我来说有点涉及,但是我会给您一些建议:

eval("tagCreditOrDebit = document.forms[0]." + tagFactor.name.substr(0,3) + "CreditOrDebitC");

This can be written in a MUCH better way: 这可以用更好的方式编写:

tagCreditOrDebit = document.forms[0][tagFactor.name.substr(0,3) + "CreditOrDebitC"];

In javascript, anywhere where you can use dotted syntax, you can use square brackets. 在javascript中,可以在任何可以使用点分语法的地方使用方括号。

document.body;
document['body'];
var b = 'body';
document[b];

Also, think about giving your forms some sort of identifier. 另外,请考虑为表单提供某种标识符。 I have no clue at all why document.forms[0] was the standard way to address a form for so long... if you decide to place another form on the page before this one, then everything will break! 我完全不知道为什么document.forms[0]这么长时间是解决表单的标准方法...如果您决定在此表单之前的页面上放置另一种表单,那么一切都会中断!

Other ways to do it include: 其他方法包括:

// HTML
<form name="myFormName">

// Javascript
var f = document.myFormName;

or 要么

<form id="myFormId">

var f = document.getElementById("myFormId")

I ended up solving this with a global variable. 我最终用一个全局变量解决了这个问题。 I originally set a value g_bHardEditsPassed to true assuming we will have no errors. 我最初将值g_bHardEditsPassed设置为true,假设我们没有错误。 Then in f_VerifyRange , everytime I return a value, I put a line before it to set the g_bHardEditsPassed variable to match. 然后在f_VerifyRange ,每次返回一个值时,都会在其前面放置一行以设置g_bHardEditsPassed变量以匹配。 Then I modified the loop to look like this... 然后我将循环修改为如下形式:

    g_bHardEditsPassed = true;

    for (var intElement = 0; intElement < document.forms[0].elements.length; intElement = intElement + 1)
    {
        if (document.forms[0].elements[intElement].name.substr(3) == "FactorAmount")
        {
            document.forms[0].elements[intElement].onblur()
            if (!g_bHardEditsPassed)
            {
                g_bHardEditsPassed = true;
                return false;
            }
        }
    }

    return true;

Thanks for everyone's suggestions. 感谢大家的建议。 I'm sure that the jQuery thing especially will be worth looking into for the future. 我确信特别值得考虑的是jQuery。

You´re not getting any success with if (!...onblur()) because the return of onblur() is always undefined when used directly. if (!...onblur())不会获得任何成功,因为直接使用onblur()的返回值始终是undefined OnBlur() is a Event Handler Function . OnBlur()事件处理函数 Like you descovered, you have to create a workaround. 就像发现您一样,您必须创建一种解决方法。

First, for the love of god and all that is holy, stop writing native javascript and help yourself to some of that jQuery :) 首先,出于对上帝的热爱和神圣的一切,请停止编写本机javascript,并帮助自己使用其中的jQuery :)

Second, start using a validation framework. 其次,开始使用验证框架。 For jQuery, jQuery Validate usually works really well. 对于jQuery, jQuery Validate通常效果很好。 It supports things like dependencies between different fields, etc. And you can also quite easily add new rules, like valid ISBN numbers, etc. 它支持诸如不同字段之间的依赖关系之类的内容。您还可以轻松添加新规则,例如有效的ISBN号等。

Edit: As for your code, I'm not sure that you can use onunload for this, as at that point there's no way back, you can't abort at that point. 编辑:至于您的代码,我不确定您是否可以为此使用onunload,因为那时候没有退路,那时候您不能中止。 You should put this code on the onsubmit event instead. 您应该将此代码放在onsubmit事件上。

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

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