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


JQuery closest()用法及代码示例


closest()是jQuery中的内置方法,它返回DOM树中所选元素的第一个祖先。此方法在搜索元素的第一个祖先时从当前元素向上遍历。文档对象模型(DOM)是万维网联盟标准。这定义用于访问DOM树中的元素。
用法:

$(selector).closest(para1, para2);

参数:它接受下面指定的两个参数:

  • para1:这指定了在DOM树中用于叙述祖先搜索的元素。
  • para2:这是一个可选参数DOM元素,可在其中找到匹配元素。

返回值:它返回所选元素的第一个祖先。


jQuery代码显示closest()方法的用法方式:

代码1:
在下面的代码中,未传递可选参数。
<html> 
  
<head> 
    <style> 
        .main * { 
            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> 
    <!-- here is the script code for performing the method -->
        $(document).ready(function() { 
            $("span").closest("ul").css({ 
                "color": "green", 
                "border": "2px solid green" 
            }); 
        }); 
    </script> 
</head> 
  
<body class="main"> 
    This is great-great grand parent element ! 
    <div style="width:600px;"> 
        This is great grand parent element ! 
        <ul> 
            This is the second ancestor element ! 
            <ul> 
                <!-- This element will be selected -->
                This is first ancestor element ! 
                <li>This is direct parent ! 
                <span>This is span the child element !</span> 
                </li> 
            </ul> 
        </ul> 
    </div> 
</body> 
  
</html>

输出:

代码2:
在下面的代码中,可选参数传递给该方法。

<html> 
  
<head> 
    <style> 
        .main * { 
            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() { 
        <!--Here among dom id first ancestor will select -->
            var item = document.getElementById("dom"); 
            $("li").closest("ul", item).css({ 
                "color": "green", 
                "border": "2px solid green" 
            }); 
        }); 
    </script> 
</head> 
  
<body class="main"> 
    This is great-great-grandparent ! 
    <div style="width:500px;"> 
        div (great-grandparent) 
        <ul id="dom"> 
            This is second ancestor ! 
            <ul id="dom"> 
                This is first ancestor ! 
                <li>This is direct parent ! 
                <span>This is span the child one !</span> 
                </li> 
            </ul> 
        </ul> 
    </div> 
</body> 
  
</html>

输出:



相关用法


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