jquery each

http://api.jquery.com/jQuery.each/

 

一、

 

  • version added: 1.0jQuery.each( collection, callback(indexInArray, valueOfElement) )

    collectionThe object or array to iterate over.

    callback(indexInArray, valueOfElement)The function that will be executed on every object.

The $.each() function is not the same as $(selector).each(), which is used to iterate, exclusively, over a jQuery object. The $.each() function can be used to iterate over any collection, whether it is a map (JavaScript object) or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time. (The value can also be accessed through the this keyword, but Javascript will always wrap the this value as an Object even if it is a simple string or number value.) The method returns its first argument, the object that was iterated.

$.each([52, 97], function(index, value) { 
  alert(index + ': ' + value); 
});

This produces two messages:

0: 52
1: 97

If a map is used as the collection, the callback is passed a key-value pair each time:

var map = { 
  'flammable': 'inflammable', 
  'duh': 'no duh' 
}; 
$.each(map, function(key, value) { 
  alert(key + ': ' + value); 
});

Once again, this produces two messages:

flammable: inflammable
duh: no duh

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

 

 

二、

 

 

.each( function(index, Element) )

function(index, Element)A function to execute for each matched element.

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.

Suppose we had a simple unordered list on the page:

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

We can select the list items and iterate across them:

$('li').each(function(index) {
    alert(index + ': ' + $(this).text());
  });
  

A message is thus alerted for each item in the list:

0: foo
1: bar

We can stop the loop from within the callback function by returning false.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值