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


Итерирует три div элемента и устанавливает их свойство цвета.

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>Нажмите здесь</div>
<div>чтобы итерировать</div>
<div>эти div элементы.</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>

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

Для доступа к объекту jQuery вместо DOM-элемента, используйте $( this ). Например:

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>
Список задач: <span>(нажмите сюда для изменения)</span>
<ul>
<li>Покушать</li>
<li>Поспать</li>
<li>Жениться</li>
</ul>
<script>
$( "span" ).click(function() {
$( "li" ).each(function() {
$( this ).toggleClass( "example" );
});
});
</script>
</body>
</html>

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

Использование return false для прерывания выполнения функции each().

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>Изменить цвета</button>
<span></span>
<div></div>
<div></div>
<div></div>
<div></div>
<div id="stop">Остановка тут</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>

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