jQuery :not() 選擇器



jQuery 中的:not() 選擇器用於選擇所有不匹配給定選擇器的元素。此選擇器可與任何 jQuery 選擇器一起使用,以選擇組中除指定元素之外的所有元素。

語法

以下是 jQuery :not() 選擇器的語法:

$(":not(selector)")

引數

以下是上述語法的描述:

  • :not(selector) 指定不選擇的元素。

示例 1

在以下示例中,我們使用 jQuery :not() 選擇器來選擇所有不具有“exclude”類的<p>元素:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("p:not(.exclude)").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <p>This paragraph will be blue.</p>
    <p class="exclude">This paragraph will not be blue.</p>
    <p>This paragraph will be blue too.</p>
</body>
</html>

執行上述程式後,選定的元素將以黃色背景突出顯示。

示例 2

在此示例中,我們選擇所有不具有 ID“exclude”的<div>元素:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            // Select all <div> elements that do not have the ID 'exclude' and set their background color to yellow
            $("div:not(#exclude)").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <div>This div will have a yellow background.</div>
    <div id="exclude">This div will not have a yellow background.</div>
    <div>This div will have a yellow background too.</div>
</body>
</html>

不具有 ID“exclude”的<div> 元素將以黃色背景突出顯示。

jquery_ref_selectors.htm
廣告