當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。