美文网首页
jquery.each return false 问题

jquery.each return false 问题

作者: 瓜田猹 | 来源:发表于2017-09-19 16:38 被阅读70次

最近在做一个验证问题时用到了for in,谁知道for in 会多循环几次(参考上篇文章 for in 循环遍历之坑),结果就改成用jquery.each,最后发现jquery.each 的return false不起作用,这是什么原因呢?

1、看下面栗子
    <div class="test">1</div>
    <div class="test">2</div>
    <div class="test">3</div>
    
    <script type="text/javascript">
        function testEach(){
            $(".test").each(function(i,ele){
                var item = $(this).text();
                if(item <= 2){
                    return false;
                    console.log("还在执行")
                }
                console.log("跳出if")
            })
            return true;
        }
        
        if(!testEach()){
            console.log("不满足条件");
        }else{
            console.log("满足条件");
        }
    </script>

打印结果

满足条件

竟然打印出“满足条件”,按常理来说上面当 item = 1时候return false,应该打印出 “不满足条件”,为什么会是满足条件呢?

$.each实际上是jquery的自定义函数, 在循环体内return false表示跳出each函数。并不能跳出testEach()这个函数,所以依然会执行each()函数后面的语句 "return true" ; 所以testEach()返回值为true

解决方案: 声明一个变量或者用for循环

<script type="text/javascript">
    function testEach(){
        var flag = true;
        $(".test").each(function(i,ele){
            var item = $(this).text();
            if(item <= 2){
                flag = false;
            }
        })
        return flag;
    }
    
    if(!testEach()){
        console.log("不满足条件");
    }else{
        console.log("满足条件");
    }

    </script>

打印结果

不满足条件
2、接下来再看看return true, 我们将return false改成 return true
function testEach(){
    $(".test").each(function(i,ele){
        var item = $(this).text();
        if(item <= 2){
            return true;
            console.log("还在执行")
        }
        console.log("跳出if")
    })
    return true;
}

if(!testEach()){
    console.log("不满足条件");
}else{
    console.log("满足条件");
}
        

打印结果

 1
 2
 3
 跳出if
 满足条件

可以看出 jquery.each 的return true相当于continue,跳出当前循环

总结:
  1. $.each实际上是jquery的自定义函数, 在循环体内return false表示跳出each函数
  2. $.each return false相当于for循环中的break
  3. $.each return true相当于for循环中的continue
  4. jq 的return false; 只是跳出循环而已,要跳出函数还是要在循环外面做(立个flag或者用for循环)

参考:[ jquery.each return false 问题]

相关文章

网友评论

      本文标题:jquery.each return false 问题

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