.slice()
.slice( start, [ end ] ) 返回: jQuery
描述: 減少匹配元素集合由索引范圍到指定的一個(gè)子集。
-
version added: 1.1.4.slice( start, [ end ] )
start一個(gè)整數(shù),指示0的位置上的元素開始被選中。如果為負(fù),則表示從集合的末尾的偏移量。
end一個(gè)整數(shù),指示0的位置上被選中的元素停止。如果為負(fù),則表示從集的末尾的偏移量。如果省略,范圍,持續(xù)到集合的末尾。
如果提供的jQuery代表了一組DOM元素,.slice()
方法從匹配元素的子集中構(gòu)造一個(gè)新的jQuery對(duì)象。所提供的start
索引標(biāo)識(shí)的設(shè)置一個(gè)集合中的元素的位置;如果end
被省略,這個(gè)元素之后的所有元素將包含在結(jié)果中。
考慮一個(gè)頁上有一個(gè)簡單的列表:
<ul> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> <li>list item 4</li> <li>list item 5</li> </ul>
我們可以應(yīng)用此方法到列表集合:
$('li').slice(2).css('background-color', 'red');
該調(diào)用的結(jié)果是一個(gè)紅色背景添加大片3,4和5項(xiàng)。請(qǐng)注意,提供的索引是從零開始的,并指在jQuery對(duì)象元素的位置,不屬于DOM樹。
最終的參數(shù)允許我們選擇的范圍,以限制進(jìn)一步。 例如:
$('li').slice(2, 4).css('background-color', 'red');
現(xiàn)在只有3和4項(xiàng)被選中。該索引數(shù)再次從零開始的;延伸的范圍,但不包括指定的索引。
負(fù)指數(shù)
jQuery的.slice()
方法是仿照的JavaScript 數(shù)組的.slice()方法。模仿的特點(diǎn)之一,它是有能力將負(fù)數(shù)傳遞start
或end
的參數(shù)。如果提供一個(gè)負(fù)數(shù),這表明立場從集的結(jié)尾開始,而不是開頭。例如:
$('li').slice(-2, -1).css('background-color', 'red');
這一次只有項(xiàng)4是變成了紅色,因?yàn)樗俏ㄒ坏捻?xiàng)目的兩個(gè)從末端( -2
)和一個(gè)從端( -1
)范圍。
Examples:
Example: Turns divs yellow based on a random slice.
<!DOCTYPE html>
<html>
<head>
<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="http://code.jquery.com/jquery-latest.min.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>
Demo:
Example: Selects all paragraphs, then slices the selection to include only the first element.
$("p").slice(0, 1).wrapInner("<b></b>");
Example: Selects all paragraphs, then slices the selection to include only the first and second element.
$("p").slice(0, 2).wrapInner("<b></b>");
Example: Selects all paragraphs, then slices the selection to include only the second element.
$("p").slice(1, 2).wrapInner("<b></b>");
Example: Selects all paragraphs, then slices the selection to include only the second and third element.
$("p").slice(1).wrapInner("<b></b>");
Example: Selects all paragraphs, then slices the selection to include only the third element.
$("p").slice(-1).wrapInner("<b></b>");