用javascript调用表单验证事件时,为什么return false了还是把表单submit了?

表单提交前,都会有定义一个验证的方法以对用户提交的内容进行限定,今天写到了这个,但出现了一个好郁闷的东西,就是一点提交了,调用我自己写的一个CheckForm()方法时,我明明写了return false了,但它还是提交到服务器了,好不郁闷!然后仔细检查才发现,原来是漏了个return,下面先看出错的代码:

 1 <script src="../js/jquery-1.6.js" type="text/javascript"></script>
 2 <script type="text/javascript">
 3     $(function () {
 4         $("#btnAdd").click(function () { CheckForm() });
 5         $("#btnSave").click(function () { CheckForm() });
 6     });
 7 
 8             
 9     function CheckForm() {
10                 
11         if ($("#ddlClassesType_2").val() == "--請選擇--") {
12             alert("請選擇表單的類型");
13             $("#ddlClassesType_2").focus();
14             return false;
15         }
16 
17         if ($("#txtWebName").val() == "") {
18             alert("請輸入網址的名稱");
19             $("#txtWebName").focus();
20             return false;
21         }
22 
23         if ($("#txtWebNameAlias").val() == "") {
24             alert("請輸入網址的別稱");
25             $("#txtWebNameAlias").focus();
26             return false;
27         }
28 
29         if ($("#ddlVisitorType").val() == "-1") {
30             alert("請選擇網址的訪問類型");
31             $("#ddlVisitorType").focus();
32             return false;
33         }
34 
35         if ($("#txtSortNo").val() == "") {
36             alert("請輸入序號");
37             $("#txtSortNo").focus();
38             return false;
39         }
40 
41         if ($("#txtWebUrl").val() == "") {
42             alert("請輸入網址");
43             $("#txtWebUrl").focus();
44             return false;
45         }
46 
47         if ($("#txtWebDesc").val() == "") {
48             alert("網址備注信息也不能為空,請輸入。");
49             $("#txtWebDesc").focus();
50             return false;
51         }
52         return true;
53     }
54 </script>

我回想了一下以前写过的javascript经验,也碰到过类似的问题,当时是用javascript直接用的,类似于下面这样子:

<asp:Button ID="btnSave" runat="server" Text="保存" Width="50px" OnClick="btnSave_Click" OnClientClick="return CheckForm();" />

看到CheckForm()前面的return 没有?其实jquery也是同理的,就是少了这个家伙,所以,只要把第4跟第5行改成下面这样子就OK了

$("#btnAdd").click(function () { return CheckForm() });
$("#btnSave").click(function () { return CheckForm() });

虽然简单,但不会的时候真的要想半天,这次把它记下来,以后也能回顾一下,希望能帮到有同样困惑的朋友。