• jQuery的遍历方法


    1、jQuery中的map使用方法

    <!DOCTYPE html>
    <html>
    <head>
      <style>p { color:red; }</style>
      <script type="text/javascript" src="/jquery/jquery.js"></script>
    </head>
    
    <body>
    <form method="post" action="">
      <fieldset>
        <div>
          <label for="two">2</label>
          <input type="checkbox" value="2" id="two" name="number[]">
        </div>
        <div>
          <label for="four">4</label>
          <input type="checkbox" value="4" id="four" name="number[]">
        </div>
        <div>
          <label for="six">6</label>
          <input type="checkbox" value="6" id="six" name="number[]">
        </div>
        <div>
          <label for="eight">8</label>
          <input type="checkbox" value="8" id="eight" name="number[]">
        </div>
      </fieldset>
    </form>
    
    <p><b>Values: </b></p>
    
    <script>
      $("p").append($(':checkbox').map(function() {
        return this.id;
      }).get().join(','));
    </script>
    
    </body>
    </html>

    jQuery通过对当前集合中的每个元素调用函数对象,写法

    .map(callback(index,element))

    2、forEach方法

    这个方法只能在非IE浏览器中使用,IE浏览器中需要写个支持,应用于数组的遍历,调用数组中的每个元素

    array.forEach(callback[, thisObject]);
    if (!Array.prototype.forEach)
    {
     Array.prototype.forEach = function(fun /*, thisp*/)
     {
      var len = this.length;
      if (typeof fun != "function")
       throw new TypeError();
     
      var thisp = arguments[1];
      for (var i = 0; i < len; i++)
      {
       if (i in this)
        fun.call(thisp, this[i], i, this);
      }
     };
    }
     
    function printBr(element, index, array) {//数组元素,元素的索引,数组本身
     document.write("<br />[" + index + "] is " + element ); 
    }
     
    [12, 5, 8, 130, 44].forEach(printBr);
    //这里是示例代码
    
    

    //这里写了一个支持方法

    注意:forEach无法在所有元素都传递给调用的函数之前终止(而for循环却有break方法),如果要提前终止,必须把forEach放在try块中,并能抛出一个异常。如果forEach()调用的函数抛出foreach.break异常,循环会提前终止:(也可以考虑用if+return的方式来跳出)

    function foreach(a,b,c){
    try{
    a.forEach(b,c);
    }catch(e){
    if(e===foreach.break)return;
    else throw e;
    }
    }
    foreach.break=new Error("StopIteration");
    }

    3、for in

    可以用来遍历数组,也可以遍历对象

    var a = {"first":1,"second":2,"third":3};

    上面的这种形式就可以用for in的方式遍历

    for(var x in a){
        alert(a[x]);
    }
  • 相关阅读:
    开发实例
    一张图解析FastAdmin中的表格列表的功能
    fastAdmin进阶
    detailFormatter bootstrapTable
    responseHandler
    自定义PDO封装类
    bootstrapTable
    Thread Safety
    FastAdmin 基本知识流程一栏
    thinkphp5 Request请求类
  • 原文地址:https://www.cnblogs.com/thecatshidog/p/5136020.html
Copyright © 2020-2023  润新知