jQuery如何使用find()?用法示例

2021年4月3日18:46:58 发表评论 1,073 次浏览

find()是jQuery中的内置方法, 用于查找所选元素的所有后代元素。它将一直遍历到DOM树中所选元素的最后一个叶子。

语法如下:

$(selector).find()

在这里, 选择器是将要找到其所有后代元素的选定元素。

参数:它不接受任何参数。

返回值:它返回所选元素的所有后代元素。

jQuery代码显示此功能的工作方式:

代码1:

在下面的代码中, 所有连接到" div"元素的" span"元素都用绿色突出显示。

<html>
  
<head>
     <style>
         .descendants * {
             display: block;
             border: 2px solid grey;
             color: lightgrey;
             padding: 5px;
             margin: 15px;
         }
     </style>
     <script src="https://ajax.googleapis.com/ajax/libs/
                  jquery/3.3.1/jquery.min.js"></script>
     <script>
         $(document).ready(function() {
             $("div").find("span").css({
                 "color": "green", "border": "2px solid green"
             });
         });
     </script>
</head>
  
<body>
  
     <div class = "descendants"
          style = "width:500px;">This is the current element !!!
         <p>This is the paragraph element !!!
             <span> This is span element !!!</span>
         </p>
         <p>This is the paragraph element !!!
             <span>This is span element !!!</span>
         </p>
     </div>
  
</body>
  
</html>

输出如下:

jQuery如何使用find()?用法示例

也可以借助带有某些参数的find()函数来找到特定元素的所有后代元素。

语法如下:

$(selector1).children("selector2")

在这里, selector1是将要找到其所有后代元素的选定元素。

参数:它接受下面指定的参数-

选择器2:这是唯一的" *"号, 它返回所选元素的所有子级。

返回值:它返回所选元素的所有子级。

代码2:

在下面的代码中, " p"元素的所有" span"元素都被选中并以绿色突出显示。

<html>
  
<head>
     <style>
         .descendants * {
             display: block;
             border: 2px solid lightgrey;
             color: grey;
             padding: 5px;
             margin: 15px;
         }
     </style>
     <script src="https://ajax.googleapis.com/ajax/libs/
                  jquery/3.3.1/jquery.min.js"></script>
     <script>
         $(document).ready(function() {
             $("p").find("*").css({
                 "color": "green", "border": "2px solid green"
             });
         });
     </script>
</head>
  
<body>
  
     <div class = "descendants" 
          style = "width:500px;">This is the current element !
         <p>This is the paragraph element !!!!
             <span>This is span 1 !!!</span>
             <span>This is span 2 !!!</span>
             <span>This is span 3 !!!</span>
             <span>This is span 4 !!!</span>
         </p>
     </div>
  
</body>
  
</html>

输出如下:

jQuery如何使用find()?用法示例

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: