zoukankan      html  css  js  c++  java
  • $().each,$.each和arr.forEach对比解析

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

    <!DOCTYPE html>
    <html >
    <head>
    <meta charset="UTF-8">   
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1"/>  
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />       
    <title>$().each,$.each和arr.forEach对比解析</title>
    <style type="text/css">
    html {}
    body {position: relative;padding: 0;margin: 0;}
    </style>
    </head>
    <body>
    <button id="m-btn">Change colors</button>
    <span></span> 
    <div>1</div> 
    <div>2</div>
    <div>3</div> 
    <div>4</div>
    <div id="stop">Stop here</div> 
    <div>5</div>
    <div>6</div>
    <script src="https://cdn.bootcss.com/jquery/1.9.0/jquery.js"></script>
    <script>
    $("#m-btn").click(function () { 
        $("div").each(function (index, domEle) { 
            // domEle == this 
    
            if (index === 1) {
                return true;  //相当于continue
            }
            $(domEle).css("backgroundColor", "yellow"); 
            if ($(this).is("#stop")) { 
                $("span").text("Stopped at div index #" + index); 
                return false;  //相当于break
            } 
        });
    });
    
    var arr = ['a', 'b', 'c', 'd', 'e'];
    arr.forEach(function(item, index) {
        if (item === 'b') {
            return true;  //相当于continue
        }
        if (item === 'c') {
            return false;  //相当于continue
        }
        console.log(index + ':' + item);
    });
    
    //$.each方法可用于遍历任何对象。如果需要退出 each 循环可使回调函数返回 false,其它返回值将被忽略。
    $.each( [0, 1, 2, 3, 4, 5, 6], function(i, n){
        if (i === 1) {
            return true;  //相当于continue
        }
        if (i === 4) {
            return false;  //相当于break
        }
    
        console.log( "Item #" + i + ": " + n );
    });
    $.each( { name: "John", lang: "JS" }, function(i, n){
        console.log( "Name: " + i + ", Value: " + n );
    });
    </script>
    </body>
    </html>


  • 相关阅读:
    docker 清理日志文件
    POJ2182 Lost Cows
    POJ3468
    楼兰图腾
    P2024 [NOI2001]食物链
    POJ1733 Parity game
    洛谷P1196 [NOI2002]银河英雄传说
    洛谷P1955 [NOI2015]程序自动分析
    CF 660 C. Uncle Bogdan and Country Happiness
    CF 660A&B
  • 原文地址:https://www.cnblogs.com/xutongbao/p/9924843.html
Copyright © 2011-2022 走看看