继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

jQuery跳出循环的方法

BIG阳
关注TA
已关注
手记 308
粉丝 68
获赞 456

对于each循环

jQuery中each类似于javascript的for循环
但不同于for循环的是在each里面不能使用break结束循环,也不能使用continue来结束本次循环,想要实现类似的功能就只能用return,对应关系如下:
break           用return false
continue      用return ture

举例如下:

//用于循环同型元素
  $("[test-div]").each(function () {       var id = $(this).attr("id").toString();       if(id=='2'){          return true;
       }       if(id == '10'){          return false;
       }
  })//用于循环json
 var json = [
     {"id":"1","ownValue":"11"},
     {"id":"2","ownValue":"22"},
     {"id":"3","ownValue":"33"},
     {"id":"4","ownValue":"44"},
     {"id":"5","ownValue":"55"} ]
$.each(json, function(idx, obj) {    if(obj.id%2==0)return true;    if(obj.id==7)return false;    console.log(obj.ownValue);
});

对于for循环

for 循环一般用于遍历某个值,用 continue 和 break 关键字跳出循环

举例如下

 for(var i=0;i<10;i++){        if(i%2==0)continue;        if(i==7)break;        console.log(i);
    }



作者:weberweber
链接:https://www.jianshu.com/p/ae86f2c11927

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP