jQuery 属性选择器

jQuery 属性选择器

属性]选择器是jQuery中内置的选择器,用于选择所有具有指定属性的元素。

语法:

$("[attribute_name]")

参数:

  • attribute_name: 这是一个必要的参数,指定要选择的属性。

示例-1:

<!DOCTYPE html>
<html>
  
<head>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
    
    <script>
        (document).ready(function() {
            ("[class]").css("color",
                             "green");
        });
    </script>
</head>
  
<body>
    <center>
  
        <!-- Class attribute-->
  
        <h3 class>GeeksforGeeks</h3>
        <p>A computer science portal for geeks</p>
  
        <!--id attribute-->
  
        <p id>Geek1</p>
  
        <!--class attribute-->
  
        <p class>Geek2</p>
        <p>Geek3</p>
  
        <!--class attribute-->
  
        <div class> Thank You! </div>
  
    </center>
</body>
  
</html>

输出:
jQuery 属性选择器

在上面的例子中,所有具有指定属性(class)的元素都被格式化为绿色,即 “GeeksforGeeks”、”Geek2 “和 “谢谢你!”。

示例-2:

<!DOCTYPE html>
<html>
  
<head>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
    
    <script>
        (document).ready(function() {
            ("[class]").css("color",
                             "green");
        });
    </script>
</head>
  
<body>
    <center>
  
        <!-- Class(demo) attribute-->
  
        <h3 class="demo">GeeksforGeeks</h3>
        <p>A computer science portal for geeks</p>
  
        <!--id attribute-->
  
        <p id>Geek1</p>
        <p>Geek2</p>
  
        <!--class(test) attribute-->
  
        <p class="test">Geek3</p>
  
        <!--class(sample) attribute-->
  
        <div class="sample"> Thank You! </div>
  
    </center>
</body>
  
</html>

输出:
jQuery 属性选择器

在上面的例子中,所有具有指定属性(class)的元素被格式化为绿色,而不是考虑属性的值。”GeeksforGeeks”、”Geek3 “和 “Thank You!”被格式化了。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程