$.each() $().each的区别

  今天看api中的css(),最后有个方法我觉得很不错,就是可以逐渐修改元素的大小,今天的主题就由此引出的,那先看一下这个应用。

     

 1   $("div").click(function() {
 2     $(this).css({
 3       width: function(index, value) {
 4         return parseFloat(value) * 1.2;
 5       }, 
 6       height: function(index, value) {
 7         return parseFloat(value) * 1.2;
 8       }
 9     });
10   });

他是用的api官网上的  css( propertyName, function(index, value) ),这里的parseFloat很重要啊,因为这里的value是string类型的,所以需要用他转换成number类型。

在看官网的时候,有个demo,我觉得写的很漂亮,就是下面这个:

1 $("div").click(function () { 
2  var html = ["The clicked div has the following styles:"]; 
3  var styleProps = $(this).css( ["width", "height", "color", "background-color"] );
4  $.each( styleProps, function( prop, value ) { 
5    html.push( prop + ": " + value );  }); 
6   $( "#result" ).html( html.join( "<br>" ) );
7 }); 

我很好奇啊,css属性还可以这样赋值用?于是就查资料,这就引出了今天的主题。

$.each()api上语法是这样的:

jQuery.each( collection, callback(indexInArray, valueOfElement) )

说是可以遍历任何对象的,这里就包含对象和数组两种,自然遍历出来的东东也不一样,如果collection是对象的话,可以遍历出对象的属性和对应的属性值,也就是回调函数中的两个参数,分别是对象的属性和对应的属性值;如果collection是数组,可以遍历出来的是数组下标和对应项的值,也就是说回调函数中的两个参数,分别是数组的下标和内容。看下面三个小例子:

1 $.each( [0,1,2], function(i, n){//collection是数组
2   alert( "Item #" + i + ": " + n );
3   alert(i);   // 0 1 2
4 });
1 $.each( { name: "John", lang: "JS" }, function(i, n){//collection是对象
2   alert( "Name: " + i + ", Value: " + n );
3   alert(i);  //name  lang
4 });
1 //其实arr1为一个二维数组,item相当于取每一个一维数组, 
2 //item[0]相对于取每一个一维数组里的第一个值 
3 //所以上面这个each输出分别为:1 4 7 
4 
5 var arr1 = [[1, 4, 3], [4, 6, 6], [7, 20, 9]] 
6 $.each(arr1, function(i, item){ 
7 alert(item[0]); 
8 }); 

看完这个,我就想到他好像还有一个兄弟,$().each()或是写作.each(),api中语法

each( function(index, Element) )

注意:element - The current element (the "this" selector can also be used)

他们的区别和联系是啥啊?共同点是,他们都是用来遍历的,区别是前者是可以遍历任何集合对象的成员,后者只能遍历jquery对象的子元素,而且后者的回调函数中的参数只能是jquery对象中子元素的下标索引值,相当于for循环,可以用return退出循环,return true相当于continue,return false 相当于 break,单独一个return也可以退出循环。

1 $("button").click(function(){//这是常见用法
2   $("li").each(function(){
3     alert($(this).text())
4   });
5 });
 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
 5 <meta charset=utf-8 />
 6 <title>JS Bin</title>
 7   <style>
 8     li{margin-bottom:30px;width:200px;}
 9   </style>
10 </head>
11 <body>
12   <ul>
13     <li>1111111111111</li>
14     <li>sssssssssss</li>
15     <li>33333333333333</li>
16     <li>ffffff</li>
17   </ul>
18   <script>
19     $(function(){//中断循环
20       $('li').each(function(index){
21         if(index==1)return true;
22         if(index==3)return false;
23         $(this).css("border","1px red solid"); 
24       });
25     });
26   </script>
27 </body>
28 </html>

效果图

 

 

posted @ 2013-02-27 14:34  enggirl  阅读(312)  评论(0编辑  收藏  举报