jQuery.each(object, [callback])
通用例遍方法,可用於例遍對象和數組。
不同於例遍 jQuery 對象的 $().each() 方法,此方法可用於例遍任何對象。回調函數擁有兩個參數:第一個為對象的成員或數組的索引,第二個為對應變量或內容。如果需要退出 each 循環可使回調函數返回 false,其它返回值將被忽略。
例遍數組,同時使用元素索引和內容。
jQuery 代碼:
$.each( [0,1,2], function(i, n){
alert( "Item #" + i + ": " + n );
});
描述:
例遍對象,同時使用成員名稱和變量內容。
jQuery 代碼:
$.each( { name: "John", lang: "JS" }, function(i, n){ alert( "Name: " + i + ", Value: " + n ); });
---------------------------
$().each(callback)
以每一個匹配的元素作為上下文來執行一個函數。
意味着,每次執行傳遞進來的函數時,函數中的this關鍵字都指向一個不同的DOM元素(每次都是一個不同的匹配元素)。而且,在每次執行函數時,都會給函數傳遞一個表示作為執行環境的元素在匹配的元素集合中所處位置的數字值作為參數(從零開始的整型)。 返回 'false' 將停止循環 (就像在普通的循環中使用 'break')。返回 'true' 跳至下一個循環(就像在普通的循環中使用'continue')。
HTML 代碼:
<img/><img/>
jQuery 代碼:
$("img").each(function(i){
this.src = "test" + i + ".jpg";
});
結果:
[ <img src="test0.jpg" />, <img src="test1.jpg" /> ]
描述:
如果你想得到 jQuery對象,可以使用 $(this) 函數。
HTML 代碼:
<button>Change colors</button>
<span></span>
<div></div>
<div></div>
<div></div>
<div></div>
<div id="stop">Stop here</div>
<div></div>
<div></div>
<div></div>
jQuery 代碼:
$("img").each(function(){
$(this).toggleClass("example");
});
描述:
你可以使用 'return' 來提前跳出 each() 循環。
HTML 代碼:
<button>Change colors</button>
<span></span>
<div></div>
<div></div>
<div></div>
<div></div>
<div id="stop">Stop here</div>
<div></div>
<div></div>
<div></div>
jQuery 代碼:
$("button").click(function () {
$("div").each(function (index, domEle) {
// domEle == this
$(domEle).css("backgroundColor", "yellow");
if ($(this).is("#stop")) {
$("span").text("Stopped at div index #" + index);
return false;
}
});
});
