jQuery的each()函数

1、$.each()--全局函数介绍

语法:全局函数  jQuery.each(collection,function(indexInArray,valueOfElement))

collection——可以是任何一个集合,不管是一个js对象或者一个数组,或者是一个json对象。


indexInArray——对象的键或者是数组的索引


valueOfElement——对象的值或者是数组的项

遍历一维数组

  <script>
    var arr = ['a','b'];
    jQuery.each(arr,function(index,value){
      console.log(index);
      console.log(value);
    })
  </script>

结果:

遍历二维数组

  <script>
    var arr = [['a','b'],['c','d']];
    jQuery.each(arr,function(index,value){
      jQuery.each(value,function(i,element){
        console.log(i);
        console.log(element);
      })
    })
  </script>

结果:

遍历对象

  <script>
    var obj = {
      name: 'zs',
      age: 18
    };
    jQuery.each(obj,function(index,value){
      console.log(index);
      console.log(value);
    })
  </script>

结果:

遍历json对象

var obj = {"a":"hello", "b":"world"}; 
jQuery.each(obj,function(index,value){
    console.log(index);
    console.log(value);
})

结果:

1、$(selector).each()

语法:$(selector).each(function(index,value))
index ——伪数组的索引
value——伪数组的项值
在DOM上处理上面用的较多

遍历li标签

  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
  </ul>
  <script>
    $('li').each(function(index,value){
      console.log(index);
      /* 打印的是形如 <li>1</li>的字符串*/
      console.log(value);
      /* 若是想输出标签中的数据,那么可以吧台看成DOM对象
      。然后用innerHTML方法,输出标签中的数据;也可以转化为
      jQuery对象形如$(value).html(),然后在打印输出,如下:
      // console.log($(value).html()); */
      console.log(value.innerHTML);
    })
  </script>

小结

  1. 遍历数据:jQuery.each(collection,function(indexInArray,valueOfElement));

  2. 遍历DOM:$(selector).each(function(index,value));

猜你喜欢

转载自www.cnblogs.com/houfee/p/9297385.html
今日推荐