jQuery [attribute=value] 選擇器



jQuery 中的 [attribute=value] 選擇器用於選擇具有特定屬性和屬性值的元素。

語法

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

$("[attribute=value]")

引數

以下是上述語法的描述:

  • attribute: 指定要匹配的屬性名稱。
  • value: 指定要匹配的精確屬性值。

示例 1

在下面的示例中,我們使用 [attribute = value] 選擇器來選擇所有包含值為“text”的“type”屬性的元素:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("input[type='text']").css("border", "2px solid blue");
        });
    </script>
</head>
<body>
    <input type="text" name="username" value="Varun">
    <input type="password" name="password" value="mypassword">
    <input type="text" name="email" value="Varun@tutorialspoint.com">
</body>
</html>

執行上述程式後,選定的元素將以實心藍色邊框突出顯示。

示例 2

在此示例中,我們選擇包含值為“password”的“type”屬性的元素:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            // Select input elements with a 'type' attribute equal to 'password' (case-insensitive)
            $("input[type='password']").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <input type="text" name="username" value="Varun">
    <input type="password" name="password" value="mypassword">
    <input type="text" name="email" value="Varun@tutorialspoint.com">
</body>
</html>

當我們執行上述程式時,選定的元素將以黃色背景顏色突出顯示。

jquery_ref_selectors.htm
廣告