W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
以每一個(gè)匹配的元素作為上下文來(lái)執(zhí)行一個(gè)函數(shù)。
意味著,每次執(zhí)行傳遞進(jìn)來(lái)的函數(shù)時(shí),函數(shù)中的this關(guān)鍵字都指向一個(gè)不同的DOM元素(每次都是一個(gè)不同的匹配元素)。而且,在每次執(zhí)行函數(shù)時(shí),都會(huì)給函數(shù)傳遞一個(gè)表示作為執(zhí)行環(huán)境的元素在匹配的元素集合中所處位置的數(shù)字值作為參數(shù)(從零開始的整型)。 返回 'false' 將停止循環(huán) (就像在普通的循環(huán)中使用 'break')。返回 'true' 跳至下一個(gè)循環(huán)(就像在普通的循環(huán)中使用'continue')。
對(duì)于每個(gè)匹配的元素所要執(zhí)行的函數(shù)
迭代兩個(gè)圖像,并設(shè)置它們的 src 屬性。注意:此處 this 指代的是 DOM 對(duì)象而非 jQuery 對(duì)象。
<img/><img/>
$("img").each(function(i){
this.src = "test" + i + ".jpg";
});
[ <img src="https://atts.w3cschool.cn/attachments/image/cimg/>, <img src="test1.jpg" /> ]
如果你想得到 jQuery對(duì)象,可以使用 $(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' 來(lái)提前跳出 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;
}
});
});
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: