jQuery :first-of-type 选择器

jQuery :first-of-type 选择器

jQuery :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 选择器

例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 选择器

支持的浏览器:

  • 谷歌浏览器90.0以上
  • 互联网浏览器9.0
  • Firefox 3.6
  • Safari 4.0
  • Opera 10.5

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程