当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


JQuery each()用法及代码示例


jQuery 中的 each() 方法指定了一个为每个匹配元素运行的函数。它是 JQuery 中广泛使用的遍历方法之一。使用这个方法,我们可以遍历 jQuery 对象的 DOM 元素,并且可以为每个匹配的元素执行一个函数。

each() 接受一个参数 function(index,element),它是一个为每个选定元素执行的回调函数。此函数进一步可选地需要两个参数,即索引和元素。因此,我们必须将回调函数传递给 each() 方法。

我们还可以从回调函数中返回 false 以提前停止循环。

用法

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

参数值

each() 方法中使用的参数值定义如下。

function(index,element):它是一个强制性参数。它是为每个选定元素执行的回调函数。它有两个参数值,定义如下。

  • index:它是一个整数值,用于指定选择器的索引位置。
  • element:它是当前元素。我们可以使用这个关键字来引用当前匹配的元素。

让我们看一些插图来清楚地理解 each() 方法。

示例 1

在此示例中,将在单击按钮时触发 each() 方法。我们将此方法应用于 li 元素。因此,此方法将迭代每个 li 元素。该函数针对每个选定的 li 执行,并使用警告框显示相应 li 元素的文本。

在这里,我们没有使用回调函数的参数值。

<!DOCTYPE html>
<html>
<head>
<title> jQuery each() method </title>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h2> Welcome to the javaTpoint.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>

输出

执行上述代码后,输出将是 -

jQuery each() method

单击该按钮后,将显示如下警告。

jQuery each() method

同样,由于四个 li 元素,将显示四个警告框。

例2

在这个例子中,我们使用回调函数的参数值 index 和 element。

我们在 li 元素上应用 each() 方法。因此,该方法将从索引 0 开始迭代 li 元素。它将在每个选定的 li 元素上执行并更改相应元素的背景颜色。

一旦函数返回false,迭代就会停止。这里有六个 li 元素,当函数到达 id = "i4" 的元素时停止。虽然是第四个元素,但是索引从0开始,所以元素的位置是3。

<!DOCTYPE html>
<html>
<head>
<title> jQuery each() method </title>

<script src="https://ajax.googleapis.com/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 javaTpoint.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>

输出

执行上述代码后,单击给定的按钮,输出将是 -

jQuery each() method



相关用法


注:本文由纯净天空筛选整理自 jQuery each() method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。