简体   繁体   English

'undefined'出现在警报中

[英]'undefined' appearing in alert

I am using Javascript to validate some code, and it works fine, but whenever I call alert to show the errors, at the beginning of the alert message I get 'undefined'. 我正在使用Javascript来验证一些代码,并且它工作正常,但每当我调用alert来显示错误时,在警报消息的开头我得到'undefined'。 So when I should expect the alert to show 'Please enter a Low Target', instead I get 'undefinedPlease enter a Low Target'. 因此,当我希望警报显示“请输入低目标”时,我得到'未定义请输入低目标'。 Can somebody tell me what is wrong with my code? 有人能告诉我我的代码有什么问题吗?

//validation
        var lowTarget;
        var highTarget;
        var errorList;
        var isValid = true;

        lowTarget = $('input[name="txtLowTarget"]').val();
        highTarget = $('input[name="txtHighTarget"]').val();

        if (lowTarget == "") {
            errorList += "Please enter a Low Target\n";
            isValid = false;
        }
        else {
            if (isNumeric(lowTarget) == false) {
                errorList += "Low Target must be numeric\n";
                isValid = false;
            }
        }

        if (highTarget == "") {
            errorList += "Please enter a High Target\n";
            isValid = false;
        }
        else {
            if (isNumeric(highTarget) == false) {
                errorList += "High Target must be numeric\n";
                isValid = false;
            }
        }

        if (isValid == true) {
            if (!(parseFloat(highTarget) > parseFloat(lowTarget))) {
                errorList += "High Target must be higher than Low Target\n";
                isValid = false;
            }
        }

        if (isValid == false) {
            alert(errorList);
        }

Assign some default value to errorList , eg empty string errorList分配一些默认值,例如空字符串

var errorList = "";

Until you do that, initial value of errorList is undefined . 在您这样做之前, errorList初始值是undefined

I was finding the same problem in my project while using 我在使用时在项目中发现了同样的问题

var try2 = document.getElementsByName("y_email").value;
alert(try2);

Now I used the following and it works well 现在我使用了以下内容,效果很好

 var try2 = document.getElementsByName("y_email")[0].value;
 alert(try2);

(So Be doubly sure that what you are using in correct format to use.) (所以请加倍确定您使用的格式是否正确使用。)

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

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