.andSelf()
.andSelf() 返回: jQuery
描述: 添加先前的堆棧元素集合到當(dāng)前組合。
version added: 1.2.andSelf()
在討論中所描述的.end()
以上,jQuery對(duì)象維護(hù)一個(gè)內(nèi)部棧,不斷變化的跟蹤對(duì)應(yīng)匹配的元素。當(dāng)DOM遍歷的方法之一被調(diào)用,一組新的元素被推入堆棧。如果前一組元素是理想的好, .andSelf()
可以提供幫助。
考慮一個(gè)面頁(yè)中簡(jiǎn)單的列表和它之后的段落:
<ul> <li>list item 1</li> <li>list item 2</li> <li class="third-item">list item 3</li> <li>list item 4</li> <li>list item 5</li> </ul>
如果我們?cè)诘谌齻€(gè)項(xiàng)目開(kāi)始,我們可以找到它之后的元素來(lái):
$('li.third-item').nextAll().andSelf() .css('background-color', 'red');
此調(diào)用的結(jié)果是一個(gè)項(xiàng)目3,4和5個(gè)紅色背景。首先,最初的選擇位于第3項(xiàng),初始化堆棧,僅包含此項(xiàng)目集。在調(diào)用.nextAll()
然后推棧設(shè)置項(xiàng)目4和5上。最后, .andSelf()
調(diào)用這兩套合并在一起,創(chuàng)建一個(gè)jQuery對(duì)象,在所有三個(gè)項(xiàng)目文件順序點(diǎn):{[<li.third-item>,<li>,<li> ]}
.
Example:
Find all divs, and all the paragraphs inside of them, and give them both classnames. Notice the div doesn't have the yellow background color since it didn't use andSelf.
<!DOCTYPE html>
<html>
<head>
<style>
p, div { margin:5px; padding:5px; }
.border { border: 2px solid red; }
.background { background:yellow; }
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div>
<p>First Paragraph</p>
<p>Second Paragraph</p>
</div>
<script>
$("div").find("p").andSelf().addClass("border");
$("div").find("p").addClass("background");
</script>
</body>
</html>