Jquery教程
Jquery动效
Jquery HTML/CSS
Jquery 事件
jquery常用

Jquery each()方法

jQuery中的 each()方法指定了一个为每个匹配元素运行的函数。它是 JQuery 中广泛使用的遍历方法之一。使用此方法,我们可以迭代jQuery对象的DOM元素,并可以为每个匹配的元素执行一个函数。
each()接受参数 function(index,element) ,这是对每个选定元素执行的回调函数。此函数还可选地需要两个参数,分别是index和element。因此,我们必须将回调函数传递给each()方法。
我们还可以从回调函数返回 false ,以尽早停止循环。

语法

$(selector).each(function(index, element))

参数值

each()方法中使用的参数值定义如下。
功能(索引,元素): 。这是必填参数。它是对每个选定元素执行的回调函数。它具有两个定义如下的参数值。
index: 是一个整数值,用于指定选择器的索引位置。 element: 是当前元素。我们可以使用此关键字来引用当前匹配的元素。
让我们看一些插图以清楚地理解 each()方法。

Example1

点击该按钮将触发 each()方法。我们将此方法应用于 li 元素。因此,此方法将遍历每个 li 元素。该函数针对每个选定的 li 执行,并使用警报框显示相应的 li 元素的文本。
此处,我们未使用该参数回调函数的值。
<!DOCTYPE html>
<html>
<head>
<title> jQuery each() method </title>
<script src="/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h2> Welcome to the lidihuo.com </h2>
<ul>
<li> First element </li>
<li> Second element </li>
<li> Third element </li>
<li> Fourth element </li>
</ul>
<p>
Click the following button to see the list of <b> li </b> elements.
</p>
<button onclick = fun()> Click me </button>
<script>
function fun(){
$(document).ready(function(){
$("li").each(function(){
alert($(this).text())
});
});
}
</script>
</body>
</html>
输出

Welcome to the lidihuo.com

  • First element
  • Second element
  • Third element
  • Fourth element

Click the following button to see the list of li elements.

类似地,由于四个 li 元素,将显示四个警报框。

Example2

在此示例中,我们使用的回调函数的参数值为 index element
我们将 each()方法应用于 li元素。因此,该方法将从索引 0 开始对li元素进行迭代。它将在每个选定的 li 元素上执行并更改相应元素的背景颜色。
一旦函数返回 false ,迭代就会停止。此处有六个 li 元素,当功能到达 id ="i4" 的元素时,该函数将停止。尽管它是第四个元素,但是索引从 0 开始,因此该元素的位置为 3
<!DOCTYPE html>
<html>
<head>
<title> jQuery each() method </title>
<script src="/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
body{
text-align: center;
}
ul{
list-style-type: none;
float: left;
}
li {
width: 40px;
height: 40px;
margin: 5px;
padding: 5px;
font-size: 20px;
float: left;
border: 2px solid blue;
}
button{
font-size: 20px;
}
</style>
</head>
<body>
<h2> Welcome to the lidihuo.com </h2>
<ul>
<li> 1 </li>
<li> 2 </li>
<li> 3 </li>
<li id = "i4"> Stop </li>
<li> 5 </li>
<li> 6 </li>
</ul>
<button onclick = "fun()"> Click me </button>
<p></p>
<script>
function fun() {
$(document).ready(function(){
$("li").each(function(index, element) {
$(element).css("background", "lightgreen");
if ($(this).is("#i4")) {
$("p").text("Index begins with 0. So, the function stopped at position: " + index ).css("fontSize", "20px");
return false;
}
});
});
}
</script>
</body>
</html>
输出

Welcome to the lidihuo.com

  • 1
  • 2
  • 3
  • Stop
  • 5
  • 6

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4