andSelf()方法将先前的选择添加到当前选择中。当脚本中有多个遍历,然后添加在上一个遍历之前匹配的内容时,该方法很有用。
您可以尝试运行以下代码来学习如何使用jQuery.andSelf()方法:
<html>
<head>
<title>jQuery andSelf() method</title>
<script src = "https://cdn.staticfile.org/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("div").find("p").andSelf().addClass("border");
});
</script>
<style>
p, div {
margin:5px;
padding:5px;
}
.border {
border: 2px solid red;
}
.background {
background:yellow;
}
</style>
</head>
<body>
<div>
<p>First Paragraph</p>
<p>Second Paragraph</p>
</div>
</body>
</html>