表單提交前,都會有定義一個驗證的方法以對用戶提交的內容進行限定,今天寫到了這個,但出現了一個好郁悶的東西,就是一點提交了,調用我自己寫的一個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() });
雖然簡單,但不會的時候真的要想半天,這次把它記下來,以后也能回顧一下,希望能幫到有同樣困惑的朋友。