Jquery变量没有更新?

时间:2012-09-21 22:00:24

标签: jquery

请查看此代码,并告诉我为什么即使我的错误被触发我的错误变量仍然尖叫0.我已经尝试并试图让他们改变。我现在只是迷失了。

validationError = 0;
$("#step1continue").click(function(){

        var fname = $('#fname');
        if (fname.val() == "") {
            fname.addClass("needsfilled");
            fname.val('Required!');
                       validationError = 1;
        } else {
                  validationError = 0;
        }

        var lname = $('#lname');
        if (lname.val() == "") {
            lname.addClass("needsfilled");
            lname.val('Required!');
                        validationError = 1;
        } else {
                 validationError = 0;
        }

        var company_name = $('#company_name');
        if (company_name.val() == "") {
            company_name.addClass("needsfilled");
            company_name.val('Required!');
                        validationError = 1;
        } else {
                  validationError = 0;
        }

        var email = $('#email');
        if (email.val() == "") {
            email.addClass("needsfilled");
            email.val('Required!');
                       validationError = 1;
        } else {
                  validationError = 0;
        }

         var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
               if (!emailReg.test(email.val())) {
                        email.addClass("needsfilled");
            email.val('Use a real email address!');
                       validationError = 1;
        } else {
                 validationError = 0;
        }

         var phone = $('#phone');
                if (phone.val() == "") {
            phone.addClass("needsfilled");
            phone.val('Required!');
                        validationError = 1;
        } else {
                  validationError = 0;
        }
                if (phone.val().length < 10) {
            phone.addClass("needsfilled");
            phone.val('10 digits minimum');
                        validationError = 1;
        } else {
                 validationError = 0;
        }   

                var phoneregxp = /^[0-9]$/;
                if (phoneregxp.test(phone.val())) {
                        phone.addClass("needsfilled");
            phone.val('Numbers ONLY');
                        validationError = 1;
        } else {
                  validationError = 0;
        }   

      alert(validationError);

});

1 个答案:

答案 0 :(得分:3)

因为您在每次成功检查时都会不断重置validationError吗?

如果(例如)#fname未填写,则将validationError设置为1.这没关系。但是你检查#lname,并且oops ...那是填写的,所以现在validationError再次为0。

而不是像疯了一样被扯开的简单开/关值,为什么每次出现错误时 INCREMENT 值都没有?

validationError = 0;
if (...) { validationError++ }
if (...) { validationError++ }
if (validationError > 0) {
   alert('You have ' + validationError + ' errors');
}