js中each函數的用法

官方說明:javascript

jQuery.each(object, [callback]) 

概述 
通用例遍方法,可用於例遍對象和數組。 

不一樣於例遍 jQuery 對象的 $().each() 方法,此方法可用於例遍任何對象。回調函數擁有兩個參數:第一個爲對象的成員或數組的索引,第二個爲對應變量或內容。若是須要退出 each 循環可以使回調函數返回 false,其它返回值將被忽略。 

參數 
objectObject 
須要例遍的對象或數組。 

callback (可選)Function 
每一個成員/元素執行的回調函數。html

each,通常用來循環 數組、對象、Dom元素java

1.循環數組jquery

  a.一維數組數組

var arr = [ "one", "two", "three", "four"]; $.each(arr, function(){ alert(this); }); 
//arr爲循環對象,上面這個each輸出的結果分別爲:one,two,three,four 
還能夠寫成:
 $.each(arr, function(i,v){ // console.log(arr[i]); // one ,two ... // console.log(this) //類型爲字符串對象 console.log(v) //one ,two ...  }); 
b.二維數組
var arr1 = [[1, 4, 3], [4, 6, 6], [7, 20, 9]] $.each(arr1, function(i, item){ alert(item[0]); }); 

 

item至關於取每個一維數組, item[0]相對於取每個一維數組裏的第一個值,因此上面這個each輸出分別爲:1 4 7 2.循環對象
var obj = { one:1, two:2, three:3, four:4}; $.each(obj, function(i) { alert(obj[i]); }); 

  循環每個屬性,輸出結果爲:1 2 3 4 函數

 3.循環Domthis

 

<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $("li").each(function(){ alert($(this).text()) }); }); }); </script>
</head>
<body>
<button>輸出每一個列表項的值</button>
<ul>
<li>Coffee</li>
<li>Milk</li>
<li>Soda</li>
</ul>
</body>
</html>
相關文章
相關標籤/搜索