Jquery的each里面用return false代替break; return ture 代替continue

本文介绍了一个使用jQuery进行表单验证的具体案例。案例中通过try...catch结构来捕获并处理异常,实现了在遍历检查过程中一旦发现不符合条件的情况即刻停止执行,并给出相应的提示信息。
复制代码
function methodone(){ 
.... 
   $.each(array,
function(){ 
   
if(条件成立){ 
     
return true
   } 
  }); 
.... 

复制代码

在一个function里有一个each,在each里某种条件 成立的话,就把这个function返回true或者false 

但是在each代码块内不能使用break和continue,要实现break和continue的功能的话,要使用其它的方式 
break----用return false; 
continue --用return ture; 

所以当我在each里想使用return true给这个function返回时,其实只是让each继续执行而以 
连each都没有中断,所以function也就不能return了 。

解决办法:通过try捕捉throw出来的错误,达到退出each、并返回错误的目标!

复制代码
function CheckBatchRow(obj) {
    
if ($(":checkbox[id$='chkSelect']:checked").size() > 0) {
        
try {
            $(
":checkbox[id$='chkSelect']:checked").each(function() {
                
var prefix = this.id.replace("chkSelect""");

                
var txtDateStart = $("#" + prefix + "txtDateStart");
                
var txtDateEnd = $("#" + prefix + "txtDateEnd");
                
if ($.trim(txtDateStart.val()) == '' || $.trim(txtDateEnd.val()) == '') {
                    txtDateStart.addClass(
"fareValidForm");
                    txtDateEnd.addClass(
"fareValidForm");
                    
throw "对不起,请您填写有效期!";
 
                }
                
else {
                    d1Arr 
= txtDateStart.val().split('-');
                    d2Arr 
= txtDateEnd.val().split('-');
                    v1 
= new Date(d1Arr[0], d1Arr[1], d1Arr[2]);
                    v2 
= new Date(d2Arr[0], d2Arr[1], d2Arr[2]);
                    
if (v2 < v1) {
                        txtDateEnd.addClass(
"fareValidForm");
                        
throw "对不起,结束日期不能小于开始日期!";
                    }
                }

                
var txtRemaindAmt = $("#" + prefix + "txtRemaindAmt");
                
if (txtRemaindAmt.val().match(/^[0-9]+$/== null) {
                    txtRemaindAmt.addClass(
"fareValidForm");
                    
throw "对不起,机票数量必须为数字!";
                }
                
else {
                    
if (txtRemaindAmt.val() < 1) {
                        txtRemaindAmt.addClass(
"fareValidForm");
                        
throw "对不起,机票数量必须大于0!";
                    }
                }

                
var txtFarePrice = $("#" + prefix + "txtFarePrice");
                
if (txtFarePrice.val().match(/^[0-9]+0$/== null) {
                    txtFarePrice.addClass(
"fareValidForm");
                    
throw "对不起,票面价必须为数字,且为10的倍数!";
                }
            });

        } 
catch (e) {
            PopupMsg(e);
            
return false;
        }

        
return CustomConfirm(obj, '您确定要更新吗?');
    }
    
else {
        PopupMsg(
"对不起,您没有修改任何项!");
        
return false;
    }
}
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值