jQuery [attribute*=value] 選擇器



在 jQuery 中,[attribute*=value] 選擇器用於選擇其屬性包含指定子字串的元素。與屬性值匹配的子字串區分大小寫。

語法

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

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

引數

以下是上述語法的描述:

  • attribute: 您要匹配的屬性名稱。
  • value: 應包含在屬性值中的子字串。

示例 1

在以下示例中,我們使用 jQuery [attribute*=value] 選擇器來選擇所有具有包含“highlight”的 class 屬性的元素:

<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="highlighted">This div has 'highlight' in its class.</div>
    <div class="notHighlighted">This div does not have 'highlight' in its class.</div>
    <div class="highlightMe">This div also has 'highlight' in its class.</div>
</body>
</html>

選定的 <div> 元素將以黃色背景顏色突出顯示。

示例 2

在此示例中,我們選擇所有具有包含“example”的 data-info 屬性的元素:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("[data-info*=example]").css("border", "2px solid blue");
        });
    </script>
</head>
<body>
    <p data-info="exampleOne">This paragraph has 'example' in its data-info attribute.</p>
    <p data-info="noExample">This paragraph does not have 'example' in its data-info attribute.</p>
    <p data-info="exampleTwo">This paragraph also has 'example' in its data-info attribute.</p>
</body>
</html>

所有選定的元素都將以實心藍色突出顯示。

jquery_ref_selectors.htm
廣告

© . All rights reserved.