each() 會為集合中的每一個匹配元素執行指定的函數,是 jQuery 裡最基礎的迴圈工具。若在函數中 return false,可以提早中止整個循環。
$(selector).each(function(index,element))
其中 function(index,element) 為必需:
index:該元素在選擇器結果中的 index 位置。element:當前的元素本身,在函數內也可以直接用 this 指代(注意 this 是原生 DOM 元素,要用 jQuery 方法時需包成 $(this))。<html>
<head>
<script type="text/javascript" src="https:///keleyi/pmedia/jquery/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("li").each(function(){
alert($(this).text())
});
});
});
</script>
</head>
<body>
<button>輸出每個列表項的值</button>
<ul>
<li></li>
<li></li>
<li>jQuery each()</li>
</ul>
</body>
</html>
代碼效果:
點擊按鈕後會依序彈出三個清單項的文字(前兩個是空字串)。實務上更常見的用法是搭配 index 做序號,或在函數中 return false 提前跳出。