jQuery Misc each()方法
jQuery中的each()方法是用来指定为每个匹配的元素运行的函数。
语法:
$(selector).each(function(index, element))
参数:此方法接受单参数function(index, element),这是必须的。它用于为每个匹配的元素运行。它包含两个参数。
- index。它持有选择器元素的索引位置。
- element。它持有当前的元素。
例子1:这个例子使用each()方法来显示每个段落元素。
<!DOCTYPE html>
<html>
<head>
<title>
jQuery Misc each() Method
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body style="text-align:center;">
<h1 style = "color:green;" >
GeeksForGeeks
</h1>
<h2>jQuery each() Method</h2>
<button>Click</button>
<p>Geeks1</p>
<p>Geeks2</p>
<p>Geeks3</p>
<!-- Script use each() method -->
<script>
(document).ready(function() {
("button").click(function() {
("p").each(function() {
alert((this).text())
});
});
});
</script>
</body>
</html>
输出:
- 在点击按钮之前

- 点击按钮后



实例2:本例使用each()方法来显示段落元素。
<!DOCTYPE html>
<html>
<head>
<title>
jQuery Misc each() Method
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body style="text-align:center;">
<h1 style = "color:green;" >
GeeksForGeeks
</h1>
<h2>jQuery each() Method</h2>
<button>Click</button>
<p>Geeks1-Geeks2-Geeks3</p>
<div style="color:lightgreen;"></div>
<!-- Script use each() method -->
<script>
(document).ready(function(){
("button").click(function(){
("p").each(function(){
("div").text($(this).text())
});
});
});
</script>
</body>
</html>
输出:
-
在点击按钮之前

-
点击按钮后

极客教程