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


JQuery closest()用法及代碼示例


closest()是 jQuery 中的內置方法,它返回 DOM 樹中所選元素的第一個祖先。該方法從當前元素開始向上遍曆,查找元素的第一祖先。文檔對象模型 (DOM) 是萬維網聯盟標準。這定義了訪問 DOM 樹中的元素。

用法:

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

參數:它接受下麵指定的兩個參數 -

  • para1:這指定了在 DOM 樹中說明祖先搜索的元素。
  • para2:這是一個可選參數 DOM 元素,可在其中找到匹配的元素。

返回值:它返回所選元素的第一個祖先。

顯示 closest() 方法工作原理的 jQuery 代碼:

示例 1:在下麵的代碼中,未傳遞可選參數。

html


<!DOCTYPE html>
<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


<!DOCTYPE html>
<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
            let 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>

輸出:

jQuery 是一個開源 JavaScript 庫,它簡化了 HTML/CSS 文檔之間的交互,它以其哲學而聞名“少寫,多做”。你可以按照這個從頭開始學習 jQueryjQuery 教程jQuery 示例.



相關用法


注:本文由純淨天空篩選整理自kundankumarjha大神的英文原創作品 jQuery closest() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。