`
lgh06
  • 浏览: 55279 次
文章分类
社区版块
存档分类
最新评论

jQuery.each()与each()

 
阅读更多

jQuery.each( array, callback )Returns:Object

Description:A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.

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 an 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 thethiskeyword, but Javascript will always wrap thethisvalue as anObjecteven if it is a simple string or number value.) The method returns its first argument, the object that was iterated.

Note:The$.each()function internally retrieves and uses thelengthproperty of the passed collection. So, if the collection has a property calledlength— e.g.{bar: 'foo', length: 10}— the function might not work as expected.

1
2
3
$.each([ 52, 97 ], function( index, value ) {
alert( index + ": " + value );
});

This produces two messages:

0: 52
1: 97

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

1
2
3
4
5
6
7
var obj = {
"flammable": "inflammable",
"duh": "no duh"
};
$.each( obj, 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 returnfalse. Returningnon-falseis the same as acontinuestatement in a for loop; it will skip immediately to the next iteration.

Examples:

Example:Iterates through the array displaying each number as both a word and numeral

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.each demo</title>
<style>
div {
color: blue;
}
div#five {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
<div id="four"></div>
<div id="five"></div>
<script>
var arr = [ "one", "two", "three", "four", "five" ];
var obj = { one: 1, two: 2, three: 3, four: 4, five: 5 };
jQuery.each( arr, function( i, val ) {
$( "#" + val ).text( "Mine is " + val + "." );
// Will stop running after "three"
return ( val !== "three" );
});
jQuery.each( obj, function( i, val ) {
$( "#" + i ).append( document.createTextNode( " - " + val ) );
});
</script>
</body>
</html>

Demo:

Example:Iterates over items in an array, accessing both the current item and its index.

1
2
3
$.each( [ "a", "b", "c" ], function( i, l ){
alert( "Index #" + i + ": " + l );
});

Example:Iterates over the properties in an object, accessing both the current item and its key.

1
2
3
$.each({ name: "John", lang: "JS" }, function( k, v ) {
alert( "Key: " + k + ", Value: " + v );
});











.each()


.each( function )Returns:jQuery

Description:Iterate over a jQuery object, executing a function 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 keywordthisrefers to the element.

Suppose you have a simple unordered list on the page:

1
2
3
4
<ul>
<li>foo</li>
<li>bar</li>
</ul>

You can select the list items and iterate across them:

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

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

0: foo
1: bar

You can stop the loop from within the callback function by returningfalse.

Note: most jQuery methods that return a jQuery object also loop through the set of elements in the jQuery collection — a process known asimplicit iteration. When this occurs, it is often unnecessary toexplicitlyiterate with the.each()method:

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

Examples:

Example:Iterate over three divs and sets their color property.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>each demo</title>
<style>
div {
color: red;
text-align: center;
cursor: pointer;
font-weight: bolder;
width: 300px;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.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>

Demo:

Example:To access a jQuery object instead of the regular DOM element, use$( this ). For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>each demo</title>
<style>
ul {
font-size: 18px;
margin: 0;
}
span {
color: blue;
text-decoration: underline;
cursor: pointer;
}
.example {
font-style: italic;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
To do list: <span>(click here to change)</span>
<ul>
<li>Eat</li>
<li>Sleep</li>
<li>Be merry</li>
</ul>
<script>
$( "span" ).click(function() {
$( "li" ).each(function() {
$( this ).toggleClass( "example" );
});
});
</script>
</body>
</html>

Demo:

Example:Usereturn falseto break out of each() loops early.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>each demo</title>
<style>
div {
width: 40px;
height: 40px;
margin: 5px;
float: left;
border: 2px blue solid;
text-align: center;
}
span {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.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, element ) {
// element == this
$( element ).css( "backgroundColor", "yellow" );
if ( $( this ).is( "#stop" ) ) {
$( "span" ).text( "Stopped at div index #" + index );
return false;
}
});
});
</script>
</body>
</html>

Demo:


分享到:
评论

相关推荐

    jQuery源码分析之jQuery.fn.each与jQuery.each用法

    本文实例讲述了jQuery源码分析之jQuery.fn.each与jQuery.each用法。分享给大家供大家参考。具体分析如下: 先上例子,下面代码的作用是:对每个选中的div元素,都给它们添加一个red类 复制代码 代码如下:$(‘div’)....

    jQuery.each-v1.10.2源码

    jQuery.each-v1.10.2源码

    浅谈jquery中的each方法$.each、this.each、$.fn.each

    jquery.each 方法 方法一 $("img").each(function(i,elem){  // i 下标 从零开始,  // elem == this  // $(elem).toggleClass("example"); $(this).toggleClass("example"); }); 方法二 $.each([1,2,3,4],...

    jQuery.each使用详解

    jQuery.each方法是jQuery的核心工具方法之一,通用例遍方法,可用于例遍对象和数组。不同于例遍 jQuery 对象的 $().each() 方法,此方法可用于例遍任何对象。通常需要两个参数 object:需要例遍的对象或数组。 ...

    jQuery的$.each()遍历数组或对象的用法

    $.each()遍历数组或对象的具体用法

    jquery里的each使用方法详解

    jQuery和jQuery对象都实 现了该方法,对于jQuery对象,只是把each方法简单的进行了委托:把jQuery对象作为第一个参数传递给jQuery的each方法.换句话 说:jQuery提供的each方法是对参数一提供的对象的中所有的子元素...

    Pro.jQuery.2.0

    Each topic is covered clearly and concisely, and is packed with the details you'll need to learn to be truly effective. The most important features are given a no-nonsense, in-depth treatment, and ...

    [jQuery.UI.1.7.jQuery用户界面库].文字版.pdf

    Over the course of this book we'll look at each of the existing components that make up the library. We will also be looking at their configuration options and trying out their methods in order to ...

    使用AJAX动态生成table表格数据和jquery.pagination.js 的分页栏

    使用jquery,动态生成table表格,使用jquery.pagination.js来实现分页栏

    jQuery.each()用法分享

    (i是索引,n是内容) 代码如下: $.each( [0,1,2], function(i, n){ alert&#40; “Item #” + i + “: ” + n &#41;; }); 例遍对象,同时使用成员名称和变量内容。(i是成员名称,n是变量内容) 代码如下: $.each( {...

    JQuery $.each遍历JavaScript数组对象实例

    声明了一个JSON字符串直接遍历,在Chrome控制台下面报错,解决方法是将JSON字符串转换为JavaScript对象

    详解Jquery 遍历数组之$().each方法与$.each()方法介绍

    $().each() 对于这个方法,在dom处理上用的比较多,如果一个html页面上面有多个checkbox,这时用$().each来处理checkbox是比较不错的; $("input[type='checkbox']").each(function...script src="jquery-1.9.0.min.js

    jquery.my.js

    用JavaScript原生封装的一个jQuery库,可供大家学习底层封装原理。有addClass 添加类,removeClass 删除类,toggleClass 切换类,each 遍历函数,show() 显示, hide() 隐藏,toggle() 切换, html() 获取或设置html...

    jquery $.each json 获取json 数据

    NULL 博文链接:https://likebin.iteye.com/blog/867876

    深入理解$.each和$(selector).each

    $(selector).each:该方法用于遍历Jquery对象 语法:$.each(obj,callback,args) ①遍历数组 var arry = [“a”,”b”,”c”,”d”,…]; $.each(arry,function(index,value){…}) 回调函数中:index 代表数组的索引 ...

    jQuery中$.each()函数的用法引申实例_.docx

    jQuery中$.each()函数的用法引申实例_.docx

    jquery的$().each和$.each的区别

    $(selector).each(function(index,element)) 这个函数和之前项目里面用到的遍历数据的函数不是同一个呀(项目里面用到的函 数:$.each(dataresource,function(index,element))),于是,就好好研究了下,果然在JS...

Global site tag (gtag.js) - Google Analytics