jQuery - andSelf() 方法



描述

andSelf() 方法将之前的选择添加到当前选择中。

当您的脚本中有多次遍历,然后添加在最后一次遍历之前匹配的内容时,此方法很有用。

语法

以下是使用此方法的简单语法:

selector.andSelf( )

参数

以下是此方法使用所有参数的描述:

  • 无。

示例

以下是一个简单的示例,展示了此方法的使用:

<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://tutorialspoint.com/jquery/jquery-3.6.0.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>

这里将在之前的选择(一个 div)和第二个选择(段落)上添加边框,如下所示:

如果您删除 andSelf() 方法,则边框将仅应用于段落。

<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://tutorialspoint.com/jquery/jquery-3.6.0.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 class = "border">
         <p class = "border">First Paragraph</p>
         <p class = "border">Second Paragraph</p>
      </div>
   </body>
</html>

这将产生以下结果:

jquery-traversing.htm
广告

© . All rights reserved.