jQuery跳出循环的方法

作者: 18587a1108f1 | 来源:发表于2017-08-11 15:20 被阅读87次

对于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);
    }

相关文章

网友评论

  • 大白PM:最好插入一些运行结果等截图,不然还需要读者自己去写代码跑一边是不是正确。
    18587a1108f1::smile: 好的!以后发文会注意的! 谢谢你~

本文标题:jQuery跳出循环的方法

本文链接:https://www.haomeiwen.com/subject/jdzlrxtx.html