如何在jQuery中使用each()

时间:2020-02-23 14:46:02  来源:igfitidea点击:

在本文中,我们将讨论jQueryeach()方法,该方法是jQuery中最重要且最常用的遍历函数之一。

jQuery each()

该方法使您可以迭代jQuery对象的DOM元素,并为每个匹配的元素执行一个函数。
您必须将回调函数传递给针对每个选定元素执行的each()方法。
回调函数是在当前DOM元素的上下文中触发的,因此您可以使用this关键字来引用当前匹配的元素。
您可以从回调函数返回false,以尽早停止循环。

这是使用jQuery each()方法的一般语法:

  • selector.each(function)

function是为每个匹配的元素触发的回调方法。
这是each()方法的必需参数。
function(index,element)具有两个参数index和element。
index一个整数值,它是所选元素的索引。
element是所选元素本身。

jQuery each()示例

以下示例演示了jQuery each()的用法。

<!doctype html>
<html>
<head>
<title>jQuery Traversing each</title>
<style>
  div {
    width: 40px;
    height: 50px;
    margin: 5px;
    float: left;
    border: 3px blue solid;
    text-align: center;
  }
  button{
    float: left;
  }    
  .highlight{
    background: yellow;
  } 
  span {
    color: red;
  }
</style>
<script src="https://code.jquery.com/jquery-2.1.1.js"></script>
</head>
<body>
<button>Click Here</button>

<div></div>
<div></div>
<div></div>
<div></div>
<div id="stop"> Stop</div>
<div></div>
<div></div>

<script>
$( "button" ).click(function() {
 $( "div" ).each(function( index,element ) {
    $( element ).text("index # "+index).addClass("highlight");
  if ( $( this ).is( "#stop" ) ) {
    $( "span" ).text( "Stopped at index #" + index );
    return false;
  }
});
});
</script>

</body>
</html>

在此示例中,单击按钮将触发each()
each()以一个function(index,element)作为参数。
each()从第一个索引(即索引0)开始迭代选定的div元素。
该函数针对每个选定的div执行,并更改当前匹配的divCSS样式。

函数返回false时,此迭代停止。
其中is()方法检查" id = stop",并且当索引为4时,传递的函数返回false,这反过来会停止迭代。