<head>
<title>each 示例</title>
<script src="jquery-1.4.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
// 對集合中的元素逐一處理
$("div").each(function (key, value) {
alert(this.innerHTML); // this 就是當前遍歷到的原生 DOM 元素
});
// 不帶參數時,用 $(this) 操作
$("div").each(function () {
alert($(this).text());
});
});
</script>
</head>
<body>
<div id="testDom">11111</div>
<div>2222</div>
<div>33333</div>
</body>
.each(function (index, element)) 的兩個參數分別是索引與元素本身。要注意的是,參數名叫什麼都可以,但 this 永遠指向當前遍歷到的原生 DOM 元素,不是 jQuery 物件。所以:
this.innerHTML、this.id。$(this).text()、$(this).css(...)。回傳 false 可以中斷整個迴圈(等同 break),回傳 true 或不回傳則繼續下一個(等同 continue)。
兩者用途不同,別搞混:
// jQuery 物件的 each:遍歷 DOM 集合
$("div").each(function (i, el) { /* ... */ });
// jQuery 的靜態方法 each:遍歷陣列或物件
$.each([1, 2, 3], function (i, val) { /* ... */ });
$.each({ a: 1, b: 2 }, function (key, val) { /* ... */ });
$(".error")$("#daLong")$("div")$("div[name=apple]")$("input:checked")很多時候不需要 each。jQuery 的絕大多數方法都會自動作用於集合中的每一個元素,例如:
$(".item").css("color", "red"); // 全部套用,不必 each
$(".item").addClass("active"); // 同上
$(".item").attr("title", "hi"); // 同上
// 只有當每個元素要做「不同」的處理時才需要 each
$(".item").each(function (i) {
$(this).css("width", (i + 1) * 10 + "px");
});
另一個常見的誤用是在 each 裡反覆做 DOM 查詢。把 $(this) 存成區域變數可以少幾次包裝:
$(".item").each(function () {
var $this = $(this); // 只包裝一次
$this.find(".title").text("x");
$this.find(".desc").text("y");
});