slice(start,[end])
从当前匹配元素集合中取出部分元素形成新的元素集合。部分元素从索引‘start’到索引‘end’。‘end’参数可以为空,部分元素将从‘start’取到最后一个元素
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
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>
<style>
div { width:40px; height:40px; margin:10px; float:left;
border:2px solid blue; }
span { color:red; font-weight:bold; }
button { margin:5px; }
</style>
</head>
<body>
<button>Turn slice yellow</button>
<span>Click the button!</span>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</body>
</html>
$("span").text('$("div").slice(' + start +
(end ? ', ' + end : '') +
').css("background", "yellow");');
将从div元素集合中取出部分div元素组成新的div元素集合。从集合中div元素索引‘start’到集合中div元素索引‘end’