?
This document uses PHP Chinese website manual Release
以每一個匹配的元素作為上下文來執(zhí)行一個函數(shù)。
意味著,每次執(zhí)行傳遞進來的函數(shù)時,函數(shù)中的this關(guān)鍵字都指向一個不同的DOM元素(每次都是一個不同的匹配元素)。而且,在每次執(zhí)行函數(shù)時,都會給函數(shù)傳遞一個表示作為執(zhí)行環(huán)境的元素在匹配的元素集合中所處位置的數(shù)字值作為參數(shù)(從零開始的整型)。 返回 'false' 將停止循環(huán) (就像在普通的循環(huán)中使用 'break')。返回 'true' 跳至下一個循環(huán)(就像在普通的循環(huán)中使用'continue')。
對于每個匹配的元素所要執(zhí)行的函數(shù)
迭代兩個圖像,并設置它們的 src 屬性。注意:此處 this 指代的是 DOM 對象而非 jQuery 對象。
<img/><img/>
$("img").each(function(i){ this.src = "test" + i + ".jpg"; });
[ <img src="test0.jpg" />, <img src="test1.jpg" /> ]
如果你想得到 jQuery對象,可以使用 $(this) 函數(shù)。
<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>
$("img").each(function(){ $(this).toggleClass("example"); });
你可以使用 'return' 來提前跳出 each() 循環(huán)。
<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>
$("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; } }); });