.andSelf()
分类:建议弃用 > 建议弃用于1.8 | 遍历 > 杂项遍历
描述:把堆栈中前一个元素的集合添加到当前集合。
该方法不能接受任何参数。
注意:该方法已经被建议弃用,现在有一个别名.addBack(),它用在jQuery 1.8版及之后的版本中。
正如讲解.end()的页面所描述的,jQuery对象保留了一个内部堆栈,以保存元素的匹配集合的变化。在调用一种DOM遍历方法的时候,新的元素集合被跟加到堆栈中。如果又想要元素的前一个集合了,.addSelf()能够帮助你。
设想有一个网页,带有一个简单的<li;>列表:
<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>
下面的代码的结果是item3、item4和item5后面有红色的背景:
$( "li.third-item" ).nextAll().andSelf() .css( "background-color", "red" );
首先,初始选择器定位到item3,初始化堆栈带有只包含这个项目的集合。调用.nextAll(),把item4和item5的集合跟回到推栈中。最后,调用.addSelf()把两个集合合并到一起,创建了一个jQuery对象,指向全部3个项目,按照它们在document中的顺序:[ <li.third-item>, <li>, <li> ]
示例
.addSelf()方法导致遍历堆栈中前一个DOM元素集合被添加到当前的集合中。在第一个示例中,顶级堆栈包含了来自.find("p")的结果集。在第二个示例中,.addSelf()把堆栈中的前一个元素集合——在这个示例中是$("div.after-addback")——添加到当前集合,选择两个div以及它们所封装的段落文本。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>andSelf demo</title>
<style>
p, div {
margin: 5px;
padding: 5px;
}
.border {
border: 2px solid red;
}
.background {
background: yellow;
}
.left, .right {
width: 45%;
float: left;
}
.right {
margin-left: 3%;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div class="left">
<p><strong>Before <code>andSelf()</code></strong></p>
<div class="before-andself">
<p>First Paragraph</p>
<p>Second Paragraph</p>
</div>
</div>
<div class="right">
<p><strong>After <code>andSelf()</code></strong></p>
<div class="after-andself">
<p>First Paragraph</p>
<p>Second Paragraph</p>
</div>
</div>
<script>
$( "div.left, div.right" ).find( "div, div > p" ).addClass( "border" );
// First Example
$( "div.before-andself" ).find( "p" ).addClass( "background" );
// Second Example
$( "div.after-andself" ).find( "p" ).andSelf().addClass( "background" );
</script>
</body>
</html>
演示结果