$(selector).each()

.each( function(index, Element) )返回: jQuery

描述: 遍历一个jQuery对象,为每个匹配元素执行一个函数。

  • 添加的版本: 1.0.each( function(index, Element) )
    • function(index, Element)
      类型:  Function()
      为每个匹配元素执行的一个函数。

.each() 方法用来让DOM循环结构更简单更不易出错。它会迭代jQuery对象中的每一个DOM元素。每次回调函数执行时,会传递当前循环次数作为参数(从0开始计数)。更重要的是,回调函数是在当前DOM元素为上下文的语境中触发的。因此关键字 this 总是指向这个元素。

假设页面上有这样一个简单的无序列表。

<ul>
    <li>foo</li>
    <li>bar</li>
</ul>

你可以选中并迭代这些列表:

$( "li" ).each(function( index ) {
  console.log( index + ": "" + $(this).text() );
});

列表中每一项会显示在下面的消息中:

0: foo 
1: bar

我们可以通过返回 false以便在回调函数内中止循环

注意: jQuery的方法,返回一个jQuery对象遍历jQuery集合中的元素 - 被称为隐式迭代的过程。当这种情况发生时,它通常不需要显式地循环的.each()方法:

// The .each() method is unnecessary here:
$( "li" ).each(function() {
  $(this).addClass( "foo" );
});
 
// Instead, you should rely on implicit iteration:
$( "li" ).addClass( "bar" );

例子:

<!DOCTYPE html>
<html>
<head>
  <style>
  div { color:red; text-align:center; cursor:pointer;
        font-weight:bolder; width:300px; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <div>Click here</div>
  <div>to iterate through</div>
  <div>these divs.</div>
<script>
    $(document.body).click(function () {
      $( "div" ).each(function (i) {
        if ( this.style.color != "blue" ) {
          this.style.color = "blue";
        } else {
          this.style.color = "";
        }
      });
    });
</script>
 
</body>
</html>

案例二:

使用 'return' 来提前结束 each() 循环

<!DOCTYPE html>
<html>
<head>
  <style>
  div { width:40px; height:40px; margin:5px; float:left;
        border:2px blue solid; text-align:center; }
  span { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <button>Change colors</button>
  <span></span>
  <div></div>
  <div></div>
 
  <div></div>
  <div></div>
  <div id="stop">Stop here</div>
  <div></div>
 
  <div></div>
  <div></div>
<script>
    $( "button" ).click(function () {
      $( "div" ).each(function ( index, domEle) {
        // domEle == this
        $( domEle ).css( "backgroundColor", "yellow" );
        if ( $(this).is( "#stop" ) ) {
          $( "span" ).text( "Stopped at div index #" + index );
          return false;
        }
      });
    });
 
</script>
 
</body>
</html>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值