- jQuery 教程
- jQuery - 首頁
- jQuery - 路線圖
- jQuery - 概述
- jQuery - 基礎
- jQuery - 語法
- jQuery - 選擇器
- jQuery - 事件
- jQuery - 屬性
- jQuery - AJAX
- jQuery DOM操作
- jQuery - DOM
- jQuery - 新增元素
- jQuery - 刪除元素
- jQuery - 替換元素
- jQuery CSS操作
- jQuery - CSS 類
- jQuery - 尺寸
- jQuery - CSS 屬性
- jQuery 效果
- jQuery - 效果
- jQuery - 動畫
- jQuery - 鏈式操作
- jQuery - 回撥函式
- jQuery 遍歷
- jQuery - 遍歷
- jQuery - 遍歷祖先元素
- jQuery - 遍歷子孫元素
- jQuery UI
- jQuery - 互動
- jQuery - 小部件
- jQuery - 主題
- jQuery 參考
- jQuery - 選擇器
- jQuery - 事件
- jQuery - 效果
- jQuery - HTML/CSS
- jQuery - 遍歷
- jQuery - 雜項
- jQuery - 屬性
- jQuery - 工具函式
- jQuery 外掛
- jQuery - 外掛
- jQuery - PagePiling.js
- jQuery - Flickerplate.js
- jQuery - Multiscroll.js
- jQuery - Slidebar.js
- jQuery - Rowgrid.js
- jQuery - Alertify.js
- jQuery - Progressbar.js
- jQuery - Slideshow.js
- jQuery - Drawsvg.js
- jQuery - Tagsort.js
- jQuery - LogosDistort.js
- jQuery - Filer.js
- jQuery - Whatsnearby.js
- jQuery - Checkout.js
- jQuery - Blockrain.js
- jQuery - Producttour.js
- jQuery - Megadropdown.js
- jQuery - Weather.js
- jQuery 有用資源
- jQuery - 問答
- jQuery - 快速指南
- jQuery - 有用資源
- jQuery - 討論
jQuery雜項each()方法
jQuery 中的 each() 方法用於迭代 jQuery 物件,對每個匹配的元素執行一個函式。換句話說,對於匹配集合中的每個元素,都會執行提供的函式。
語法
以下是 jQuery 雜項 each() 方法的語法:
$(selector).each(function(index,element))
引數
以下是上述語法的描述:
- function: 對每個匹配元素執行的函式。
- index: 匹配集合中當前元素的基於零的索引。
- element: 正在處理的當前 DOM 元素。
示例 1
在下面的示例中,我們使用 each() 方法來更改每個段落的文字:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").each(function(index, element) {
$(element).text("Paragraph " + (index + 1));
});
});
</script>
</head>
<body>
<p>First paragraph</p>
<p>Second paragraph</p>
<p>Third paragraph</p>
</body>
</html>
執行後,它根據段落元素在集合中的位置,將每個 p 元素的文字更改為“段落 1”、“段落 2”和“段落 3”。
示例 2
在這個示例中,我們使用 each() 方法更改每個列表項的背景顏色:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("li").each(function(index, element) {
var colors = ["lightblue", "lightgreen", "yellow"];
$(element).css("background-color", colors[index % colors.length]);
});
});
</script>
</head>
<body>
<ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
<li>List item 4</li>
</ul>
</body>
</html>
執行後,它會根據列表項在集合中的位置,以迴圈模式將每個 li 元素的背景顏色設定為“紅色”、“綠色”或“藍色”。
jquery_ref_miscellaneous.htm
廣告
