jQuery [attribute~=value] 選擇器



在 jQuery 中,[attribute~=value] 用於選擇屬性值包含指定值(在空格分隔的列表中)的元素。

換句話說,它選擇指定屬性的值完全等於給定值或在空格分隔的列表中包含給定值的元素。

語法

以下是 jQuery 中 [attribute~=value] 選擇器的語法:

$("[attribute~='value']")

引數

以下是上述語法的描述:

  • attribute: 將檢查其值的屬性。
  • value: 屬性值中應包含的詞語。該值必須是一個完整的詞,而不是一個詞的一部分。

示例 1

在下面的示例中,我們使用 jQuery [attribute~=value] 選擇器來選擇類屬性中包含 "highlight" 類的所有元素:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("[class~=highlight]").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <div class="highlight">This div will be highlighted.</div>
    <div class="nohighlight">This div will not be highlighted.</div>
    <div class="highlight another-class">This div will also be highlighted.</div>
</body>
</html>

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

示例 2

在這個示例中,我們選擇包含 "feature" 的 data 屬性的元素:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("[data-tags~=feature]").css("border", "2px solid red");
        });
    </script>
</head>
<body>
    <div data-tags="feature new">This div has the 'feature' tag.</div>
    <div data-tags="old popular">This div does not have the 'feature' tag.</div>
    <div data-tags="feature popular">This div also has the 'feature' tag.</div>
</body>
</html>

執行上述程式後,選定的元素將應用一個實心的紅色邊框。

jquery_ref_selectors.htm
廣告