jQuery :nth-child() 選擇器


jQuery 中的 :nth-child() 選擇器用於選擇與其父元素無關的、第 n 個子元素。

語法

語法如下 −

:nth-child(n|even|odd|formula)

上述語法中,n 為匹配的每個子元素的索引。even 引數選擇偶數個子元素,而 odd 選擇奇數個子元素。

示例

下面我們來看一個實現 jQuery :nth-child() 選擇器的示例 −

<!DOCTYPE html>
<html>
<head>
<style>
   .one {
      color: white;
      background-color: green;
      font-size: 16px;
      border: 2px blue solid;
   }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $("p:nth-child(2)").addClass("one");
   });
</script>
</head>
<body>
<h1>Match Details</h1>
<p>Date: 29th October 2019</p>
<p>Timings: 3PM TO 8PM</p>
<p>Ground: Lords</p>
<p> Entry begins 2PM</p>
</body>
</html>

輸出

輸出如下 −

更新於: 2019 年 11 月 05 日

507 次瀏覽

開啟 職業生涯

獲取認證,完成課程

開始學習
廣告
© . All rights reserved.