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


Find the very previous sibling of 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
37
38
39
40
41
42
43
44
45
46
47
48
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>prev demo</title>
<style>
div {
width: 40px;
height: 40px;
margin: 10px;
float: left;
border: 2px blue solid;
padding: 2px;
}
span {
font-size: 14px;
}
p {
clear: left;
margin: 10px;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div></div>
<div></div>
<div><span>has child</span></div>
<div></div>
<div></div>
<div></div>
<div id="start"></div>
<div></div>
<p><button>Go to Prev</button></p>
<script>
var $curr = $( "#start" );
$curr.css( "background", "#f99" );
$( "button" ).click(function() {
$curr = $curr.prev();
$( "div" ).css( "background", "" );
$curr.css( "background", "#f99" );
});
</script>
</body>
</html>

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

For each paragraph, find the very previous sibling that has a class "selected".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>prev demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div><span>Hello</span></div>
<p class="selected">Hello Again</p>
<p>And Again</p>
<script>
$( "p" ).prev( ".selected" ).css( "background", "yellow" );
</script>
</body>
</html>

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