.each()
.each( function(index, Element) ) 返回: jQuery
描述: 遍歷一個(gè)jQuery對(duì)象,為每一個(gè)匹配元素執(zhí)行一個(gè)函數(shù)。
-
version added: 1.0.each( function(index, Element) )
function(index, Element)每一個(gè)匹配元素執(zhí)行一個(gè)函數(shù)
.each() 方法用來(lái)讓DOM循環(huán)結(jié)構(gòu)更簡(jiǎn)單更不易出錯(cuò)。它會(huì)迭代jQuery對(duì)象中的每一個(gè)DOM元素。每次回調(diào)函數(shù)執(zhí)行時(shí),會(huì)傳遞當(dāng)前循環(huán)次數(shù)作為參數(shù)(從0開(kāi)始計(jì)數(shù))。更重要的是,回調(diào)函數(shù)是在當(dāng)前DOM元素為上下文的語(yǔ)境中觸發(fā)的。因此關(guān)鍵字 this 總是指向這個(gè)元素。
假設(shè)頁(yè)面上有這樣一個(gè)簡(jiǎn)單的無(wú)序列表。
<ul>
<li>foo</li>
<li>bar</li>
</ul>
我們可以選中并迭代這些列表:
$('li').each(function(index) {
alert(index + ': ' + $(this).text());
});
列表中每一項(xiàng)會(huì)顯示在下面的消息中:
0: foo
1: bar
我們可以通過(guò)返回 false以便在回調(diào)函數(shù)內(nèi)中止循環(huán)。
Examples:
Example: 遍歷三個(gè)div并設(shè)置它們的color屬性。
<!DOCTYPE html>
<html>
<head>
<style>
div { color:red; text-align:center; cursor:pointer;
font-weight:bolder; width:300px; }
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div>Click here</div>
<div>to iterate through</div>
<div>these divs.</div>
<script>
$(document.body).click(function () {
$("div").each(function (i) {
if (this.style.color != "blue") {
this.style.color = "blue";
} else {
this.style.color = "";
}
});
});</script>
</body>
</html>
Demo:
Example: 如果你不想要普通的DOM元素,而想獲得的是jQuery對(duì)象的話,使用$(this) 函數(shù)。例如:
<!DOCTYPE html>
<html>
<head>
<style>
ul { font-size:18px; margin:0; }
span { color:blue; text-decoration:underline; cursor:pointer; }
.example { font-style:italic; }
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
To do list: <span>(click here to change)</span>
<ul>
<li>Eat</li>
<li>Sleep</li>
<li>Be merry</li>
</ul>
<script>
$("span").click(function () {
$("li").each(function(){
$(this).toggleClass("example");
});
});
</script>
</body>
</html>
Demo:
Example: 你可以使用 'return' 來(lái)提前結(jié)束 each() 循環(huán)。
<!DOCTYPE html>
<html>
<head>
<style>
div { width:40px; height:40px; margin:5px; float:left;
border:2px blue solid; text-align:center; }
span { color:red; }
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<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>
<script>
$("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;
}
});
});
</script>
</body>
</html>