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


Turns divs yellow based on a random slice.

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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>slice demo</title>
<style>
div {
width: 40px;
height: 40px;
margin: 10px;
float: left;
border: 2px solid blue;
}
span {
color: red;
font-weight: bold;
}
button {
margin: 5px;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p><button>Turn slice yellow</button>
<span>Click the button!</span></p>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<script>
function colorEm() {
var $div = $( "div" );
var start = Math.floor( Math.random() * $div.length );
var end = Math.floor( Math.random() * ( $div.length - start ) ) +
start + 1;
if ( end === $div.length ) {
end = undefined;
}
$div.css( "background", "" );
if ( end ) {
$div.slice( start, end ).css( "background", "yellow" );
} else {
$div.slice( start ).css( "background", "yellow" );
}
$( "span" ).text( "$( 'div' ).slice( " + start +
(end ? ", " + end : "") +
").css( 'background', 'yellow' );" );
}
$( "button" ).click( colorEm );
</script>
</body>
</html>

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

Selects all paragraphs, then slices the selection to include only the first element.

1
$( "p" ).slice( 0, 1 ).wrapInner( "<b></b>" );

Selects all paragraphs, then slices the selection to include only the first and second element.

1
$( "p" ).slice( 0, 2 ).wrapInner( "<b></b>" );

Selects all paragraphs, then slices the selection to include only the second element.

1
$( "p" ).slice( 1, 2 ).wrapInner( "<b></b>" );

Selects all paragraphs, then slices the selection to include only the second and third element.

1
$( "p" ).slice( 1 ).wrapInner( "<b></b>" );

Selects all paragraphs, then slices the selection to include only the third element.

1
$( "p" ).slice( -1 ).wrapInner( "<b></b>" );