標籤:jquery each 跳出及返回問題
無意中用到jquery 中的each,來源程式是這樣寫的
function verify(){ $("input").each(function (i,n){ var search_eml = /^[\w\-\.][email protected][\w\-\.]+(\.\w+)+$/; var isMobile=/^(?:13\d|15\d)\d{5}(\d{3}|\*{3})$/; var isPhone=/^((0\d{2,3})-)?(\d{7,8})(-(\d{3,}))?$/; if($(this).val().trim()==''){ alert($(this).attr("placeholder")+"不可為空"); return false; } if($(this).attr("id")=='tel'){ if($(this).val().trim().length!=11){ alert("請在'"+$(this).attr("placeholder")+"'輸入正確格式 !"); $(this).focus(); return false; } } if($(this).attr("id")=='email'){ if(!search_eml.test($(this).val())){ alert("請在'"+$(this).attr("placeholder")+"'輸入正確格式 !"); $(this).focus(); return false; } } }) return true; }}
原本以為會在調用處返回true或false但是結果是在調用處沒有返回任何東西,搜尋關於each的資料時發現
break; 等同於 return false;
continue; 等同於 return true;
也就是說 return ture 或 return false 表示的是當前迴圈是否跳出,是否繼續,所以做出如下修改.
function verify(){ var v = '1'; $("input").each(function (i,n){ var search_eml = /^[\w\-\.][email protected][\w\-\.]+(\.\w+)+$/; var isMobile=/^(?:13\d|15\d)\d{5}(\d{3}|\*{3})$/; var isPhone=/^((0\d{2,3})-)?(\d{7,8})(-(\d{3,}))?$/; if($(this).val().trim()==''){ alert($(this).attr("placeholder")+"不可為空"); v = '0'; return false; } if($(this).attr("id")=='tel'){ if($(this).val().trim().length!=11){ alert("請在'"+$(this).attr("placeholder")+"'輸入正確格式 !"); $(this).focus(); v = '0'; return false; } } if($(this).attr("id")=='email'){ if(!search_eml.test($(this).val())){ alert("請在'"+$(this).attr("placeholder")+"'輸入正確格式 !"); $(this).focus(); v = '0'; return false; } } if(v=='0'){ return false } }) if(v=='0'){ return false }else{ return true; }}
在jquery each 中想要跳出當前迴圈(break)需要使用 return false,想要執行下一個(continue)使用return true;所以在你在each的內建函數中寫return false時是不會返回調用函數處的.