2011-09-23 173 views
0

我使用这个检测的窗体上的错误...为什么这不工作的JavaScript?

var error = false; 

if (val === '') { 

    error = true; 
} 

if (error = true) { 

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

其实很简单,但没有工作,我失去了一些愚蠢的事?变量错误是默认值false

如果发现错误,它是true

如果发现错误为true它会阻止提交表单吗?

回答

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(); 
    }); 
} 
+0

的代码仍不能从根本上打破因为他订阅点击提交,以防止事件发生,但从来没有删除它们。 – JohnD

+0

@JohnD - 随意提供另一个答案中的额外信息。有了这样的问题,通常会有许多问题需要关注。 ')' –

0

你应该做在提交事件处理程序的检查:

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

    var error = false; 

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

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