您的位置:首页 > Web前端 > JQuery

jQuery.each()函数(译)

2016-01-26 18:46 736 查看
http://www.sitepoint.com/jquery-each-function-examples/ 原文地址

jQuery 的each()函数是一个相当重要的扩展。这个函数是一个jQuery最重要和最常用的功能。在本文中,我们将找出原因并研究其细节明白如何使用它。

什么是jQuery.each()?

jQuery的 each()函数用于循环JQ对象的每一个元素。如果你没有用过jQuery,我提醒你一下jQuery对象是一个对象,它包含一个或多个DOM元素,并公开所有jQuery函数。 它是非常有用的多元化的DOM操作,循环任意数组和对象属性。除了这个函数,jQuery提供了一个具有相同名称的helper函数,可以调用之前没有选择或创建的DOM元素。在接下来的部分让我们了解更多。

each()函数语法

下面的示例选择web页面上的每个div和输出的index和ID。一个可能的输出是:“div0:header”,“div1:body”,“div2:footer”。

// DOM ELEMENTS
$('div').each(function (index, value) {
console.log('div' + index + ':' + $(this).attr('id'));
});


在这种情况下,遍历对象是作为第一个参数。在这个例子中,我展示了如何遍历一个数组:

// ARRAYS
var arr = [
'one',
'two',
'three',
'four',
'five'
];
$.each(arr, function (index, value) {
console.log(value);

// Will stop running after "three"
return (value !== 'three');
});
// Outputs: one two three


在最后一个例子遍历一个对象的属性:

// OBJECTS
var obj = {
one: 1,
two: 2,
three: 3,
four: 4,
five: 5
};
$.each(obj, function (index, value) {
console.log(value);
});
// Outputs: 1 2 3 4 5


所有的这些都需要一个回调函数的,回调的上下文,this为第二个参数,这是当前值。然而,由于上下文将永远是一个对象,原始值必须被包含。因此,绝对意义上的当前值和上下文不一定会有。第一个参数是当前序号(数组)或字符串(对象)的索引。

1. 基本 jQuery.each() 例子

$('a').each(function (index, value){
console.log($(this).attr('href'));
});


$('a').each(function (index, value){
var link = $(this).attr('href');

if (link.indexOf('http://') === 0) {
console.log(link);
}
});


2. jQuery.each() Array Example

var numbers = [1, 2, 3, 4, 5, 6];
$.each(numbers , function (index, value){
console.log(index + ':' + value);
});


输出: 0:1, 1:2, 2:3, 3:4, 4:5, and 5:6.

3. jQuery.each() JSON Example

var json = [
{ 'red': '#f00' },
{ 'green': '#0f0' },
{ 'blue': '#00f' }
];

$.each(json, function () {
$.each(this, function (name, value) {
console.log(name + '=' + value);
});
});


输出:red=#f00, green=#0f0, blue=#00f.

4. jQuery.each() Class Example

<div class="productDescription">Red</div>
<div>Pink</div>
<div class="productDescription">Orange</div>
<div class="generalDescription">Teal</div>
<div class="productDescription">Green</div>


$.each($('.productDescription'), function (index, value) {
console.log(index + ':' + $(value).text());
});


输出:0:Red, 1:Orange, 2:Green.

$('.productDescription').each(function () {
console.log($(this).text());
});


输出:

Red

Orange

Green

5. jQuery .each() Delay Example

$('#5demo').bind('click', function (e) {
$('li').each(function (index
4000
) {
$(this).css('background-color', 'orange')
.delay(index * 200)
.fadeOut(1500);
});
e.preventDefault();
});


总结

我们应该皆可能多的使用each()函数,它有很好的执行效率能节省很多我们的时间。在此之前我们可能更多的会考虑使用ES5的foreach函数。

记住:

$.each() and $(selector).each() are two different methods defined in two different ways.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  函数