jQuery [attribute$=value] 选择器



jQuery 中的[attribute$=value] 选择器用于选择属性值以特定字符串结尾的元素。

当我们需要根据属性值结尾来定位元素时,此选择器非常有用,例如文件扩展名、类名或 URL 结尾。

语法

以下是 jQuery 中 [attribute$=value] 选择器的语法:

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

参数

以下是上述语法的描述:

  • attribute: 您要匹配的属性名称。
  • value: 您要在属性值中匹配的结尾字符串。区分大小写。

示例 1

在以下示例中,我们使用 [attribute$=value] 选择器来选择所有以“.pdf”结尾的 href 属性:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("a[href$='.pdf']").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <a href="document.pdf">PDF Document</a><br>
    <a href="image.jpg">JPEG Image</a><br>
    <a href="report.pdf">PDF Report</a><br>
    <a href="profile.html">HTML Profile</a>
</body>
</html>

执行上述程序后,选定的元素将以黄色背景颜色突出显示。

示例 2

在此示例中,我们选择所有 href 属性以“.png”结尾的元素:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("img[src$='.png']").css("border", "2px solid blue");
        });
    </script>
</head>
<body>
    <img src="photo.png" alt="PNG Image"><br>
    <img src="photo.jpg" alt="JPEG Image"><br>
    <img src="icon.png" alt="PNG Icon"><br>
    <img src="avatar.gif" alt="GIF Avatar">
</body>
</html>

执行上述程序后,选定的元素将以实心蓝色突出显示。

jquery_ref_selectors.htm
广告