jQuery [attribute^=value] 選擇器



jQuery 中的[attribute^=value] 選擇器用於選擇屬性值以特定值開頭的元素。換句話說,它允許您根據屬性值的開頭部分來定位元素。

語法

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

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

引數

以下是上述語法的描述:

  • attribute: 指定要匹配的屬性。
  • value: 屬性值應該以該值開頭。

示例 1

在下面的示例中,我們使用 jQuery [attribute^=value] 選擇器來選擇“href 屬性”以“https://”開頭的元素:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("a[href^='https://']").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <a href="https://example.com">Secure Example</a><br>
    <a href="http://example.com">Non-Secure Example</a><br>
    <a href="https://openai.com">OpenAI</a><br>
    <a href="https://google.com">Google</a>
</body>
</html>

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

示例 2

在這裡,我們選擇所有 src 屬性以“https://”開頭的影像元素:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("img[src^='https://']").css("border", "2px solid green");
        });
    </script>
</head>
<body>
    <img src="https://example.com/image1.jpg" alt="Image 1"><br>
    <img src="http://example.com/image2.jpg" alt="Image 2"><br>
    <img src="https://openai.com/logo.png" alt="Logo"><br>
    <img src="https://google.com/banner.jpg" alt="Banner">
</body>
</html>

執行上述程式後,選定的影像元素將以實心綠色突出顯示。

jquery_ref_selectors.htm
廣告

© . All rights reserved.