
- 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
广告