Примеры для jQuery.each()


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>

Демонстрация:

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 );
});

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 );
});