jQuery如何使用:first-of-type选择器?用法示例

2021年3月31日12:33:33 发表评论 961 次浏览

:first-of-type选择器用于选择所有作为其父级的第一个子级(特定类型)的元素。

语法如下:

$(":first-of-type")

以下示例说明了jQuery中的:first-of-type选择器:

范例1:本示例将其父母的第一个标题(div标签)的背景颜色更改为绿色, 将文本颜色更改为白色。

<!DOCTYPE html>  
<html>  
  
<head> 
     <title> 
         jQuery | :first-of-type Selector
     </title>
          
     <script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
     </script>
      
     <!-- Script to use first-of-child selector -->  
     <script>
         $(document).ready(function() {
             $("h4:first-of-type").css({
                 "background-color": "green", "color": "white"
             });
         });
     </script>
          
     <style>
         option {
             font-weight: bold;
             font-size: 25px;
             color: green;
         }
         select {
             font-weight: bold;
             font-size: 25px;
             color: green;
         }
     </style>
</head> 
      
<body style = "text-align:center; width: 500px; margin: auto">  
     <h1>  
         jQuery | :first-of-type Selector
     </h1>  
  
     <div style = "border:1px solid blue;">
         <h4>The first heading in first div.</h4>
         <h4>The last heading in first div.</h4>
     </div><br>
   
     <div style = "border:1px solid blue;">
         <h4>The first heading in second div.</h4>
         <h4>The last heading in second div.</h4>
     </div>
</body>  
  
</html>

输出如下:

jQuery如何使用:first-of-type选择器1

范例2:本示例将<body>标签的第一个标题的背景颜色更改为绿色, 将文本颜色更改为白色。

<!DOCTYPE html>  
<html>  
  
<head> 
     <title> 
         jQuery | :first-of-type Selector
     </title>
  
     <script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
     </script>
      
     <!-- Script to use first-of-child selector -->
     <script>
         $(document).ready(function() {
             $("h4:first-of-type").css({
                 "background-color": "green", "color": "white"
             });
         });
     </script>
      
     <style>
         option {
             font-weight: bold;
             font-size: 25px;
             color: green;
         }
         select {
             font-weight: bold;
             font-size: 25px;
             color: green;
         }
     </style>
</head> 
  
<body style = "text-align:center; width: 500px; margin: auto">  
     <h1>  
         jQuery | :first-of-type Selector
     </h1>  
      
     <h4>The first heading in body.</h4>
   
     <h4>The last heading in body.</h4>
</body>  
  
</html>

输出如下:

jQuery如何使用:first-of-type选择器2

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: