.andSelf()

.andSelf() 官网原E文: jQuery

描述: 添加先前的堆栈元素集合到当前组合。

  • version added: 1.2.andSelf()

在讨论中所描述的.end()以上,jQuery对象维护一个内部栈,不断变化的跟踪对应匹配的元素。当DOM遍历的方法之一被调用,一组新的元素被推入堆栈。如果前一组元素是理想的好, .andSelf()可以提供帮助。

考虑一个面页中简单的列表和它之后的段落:

<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>

如果我们在第三个项目开始,我们可以找到它之后的元素来:

$('li.third-item').nextAll().andSelf()
  .css('background-color', 'red');

此调用的结果是一个项目3,4和5个红色背景。首先,最初的选择位于第3项,初始化堆栈,仅包含此项目集。在调用.nextAll()然后推栈设置项目4和5上。最后, .andSelf()调用这两套合并在一起,创建一个jQuery对象,在所有三个项目文件顺序点:{[<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>

Demo:

jQuery 1.6 API 中文版Clove整理、修订