码迷,mamicode.com
首页 > Web开发 > 详细

jQuery的each()函数

时间:2018-07-12 00:33:17      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:对象   obj   rip   sele   fun   个数   lock   col   end   

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));

 

jQuery的each()函数

标签:对象   obj   rip   sele   fun   个数   lock   col   end   

原文地址:https://www.cnblogs.com/houfee/p/9297385.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!