each()

今天写东西的时候要用jQuery里面的each()方法,用this的时候一脸懵逼==!,就去官网看了学习总结一下。官网地址:http://api.jquery.com/each/

.each(function)
Description: Iterate over a jQuery object, executing a function for
each matched element.

function
Type: Function( Integer index, Element element )
A function to execute for each matched element.

这是each的详细介绍:The .each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element.


最后一句很关键,each()方法中的this代表的是遍历时候的每一个元素,就是说在each()方法执行的时候执行上下文环境就是每个DOM元素。

<!doctype html>
<html>
<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<ul>
    <li>foo</li>
    <li>bar</li>
</ul>
<script type="text/javascript">
    $( "li" ).each(function( index ) {
/*      
    下面的this就代表了每一个DOM元素而不是jQuery对象
    如果想用jQuery对象只要$(this)就可以了
    下面两个输出是一样的
*/
    console.log( "index is:"+index + ", " + "innerHTML is:"+this.innerHTML);  
     console.log( "index is:"+index + ", " + "innerHTML is:"+$(this).html()); 
     //index is:0, innerHTML is:foo
     //index is:1, innerHTML is:bar

});
</script>
</body>
</html>

Use return false to break out of each() loops early.

使用return false来跳出each()方法的循环

<!doctype html>
<html>
<head>
   <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
  <style>
  div {
    width: 40px;
    height: 40px;
    margin: 5px;
    float: left;
    border: 2px blue solid;
    text-align: center;
  }
  span {
    color: red;
  }
  </style>
<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, element ) {
    // element == this
    $( element ).css( "backgroundColor", "yellow" );
    if ( $( this ).is( "#stop" ) ) {
      $( "span" ).text( "Stopped at div index #" + index );
      return false;
    }
  });
});
</script>
</body>
</html>

当each()执行到id为stop的时候就结束了。

点击前:
这里写图片描述

点击后:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值