为什么这个工作不正常?

时间:2011-09-23 01:54:23

标签: javascript variables

我用它来检测表单上的错误...

var error = false;

if (val === '') {

    error = true;
}

if (error = true) {

    $('#joinForm .submit').click(function(event) {
        event.preventDefault();
    });
}

简单但真的不行,我错过了一些愚蠢的东西吗?变量错误是默认 false

如果发现错误,则为真

如果发现错误为真,则会阻止提交表单吗?

2 个答案:

答案 0 :(得分:3)

var error = false;

if (val === '') { // <<< This checks type first, then value
                  //     An empty '' variable is not type-equivalent
                  //     to a (boolean) false value
    error = true;
}

if (error = true) { // <<< You're setting a variable here, which means
                    //     means that you're testing if the variable
                    //     assignment itself is successful, you'll get
                    //     a true result in most cases, and except with
                    //     things like while loops, you shouldn't use this
                    //     form.
                    // Maybe you want == (falsy)? Or === (type-checked)?
    $('#joinForm .submit').click(function(event) {
        event.preventDefault();
    });
}

答案 1 :(得分:0)

您应该在提交事件处理程序中进行检查:

$('#joinForm').submit(function(event) {

    var error = false;

    if (val === '') {
        error = true;
    }

    if (error) {
        event.preventDefault();
    }
});