当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


JQuery find()用法及代码示例

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> 

输出:

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

$(selector1).children("selector2")

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

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

  • selector2:这只是“*” 符号,它返回所选元素的所有子元素。

返回值:它返回所选元素的所有子元素。
代码#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 是一个开源 JavaScript 库,它简化了 HTML/CSS 文档之间的交互,它以其哲学而闻名“少写,多做”.
你可以按照这个从头开始学习 jQueryjQuery 教程jQuery 示例.



相关用法


注:本文由纯净天空筛选整理自kundankumarjha大神的英文原创作品 jQuery find() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。