Jquery教程
Jquery动效
Jquery HTML/CSS
Jquery 事件
jquery常用

jQuery :nth-​​child选择器

:nth-​​child()选择器用于根据元素的位置匹配元素,而与类型无关它的父母。此选择器用于根据元素在一组同级中的位置来匹配它们。它匹配每个元素,即第n个子元素。
如果必须选择第n个子元素,则可以使用 : nth-​​of-type 选择器。

语法

使用 :nth-​​child 选择器的语法如下。
:nth-child(n | odd | even | formula)

参数值

上面语法中提到的值定义如下。
n: 上述语法中的 n 必须为整数。它代表每个要匹配的孩子的索引。此参数指示选择器,以选择以指定索引值存在的子级。第一个元素的索引号为1。
odd: 它选择每个奇数子元素。
even: 选择每个偶数子元素。
formula: 它选择出现在公式值处的子元素。查找不同孩子的公式为 an + b
如果我们考虑a = 2和b = 1,则公式将为2n + 1,它将仅选择索引值为1、3、5,..... index的元素。要求解该公式,我们可以将n的值设置为0、1、2,.... n。
现在,让我们来看一个使用: nth-的所有参数值的示例子选择器。

示例

在此示例中,我们使用了 ::nth-child(n) 。从1到10共有十个列表项,四个按钮分别名为 :nth-​​child(7),奇数,偶数, nth-child(4n + 4)。第一个按钮将选择索引号为7的列表项,第二个按钮将选择奇数列表项,第三个按钮将选择偶数列表项,第四个按钮将选择索引值为4和8的列表项。
我们必须单击给定的按钮才能看到效果。
<html>
<head>
<title> jQuery :nth-child selector </title>
<script src = "/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h1> Welcome to the lidihuo.com </h1>
<h2> It is an example of using the jQuery :nth-child selector. </h2>
<ul>
<li> 1 </li>
<li> 2 </li>
<li> 3 </li>
<li> 4 </li>
<li> 5 </li>
<li> 6 </li>
<li> 7 </li>
<li> 8 </li>
<li> 9 </li>
<li> 10 </li>
</ul>
<br/>
<p> Click the following buttons to see the effect. </p>
<button id = "n"> :nth-child(7) </button>
<button id = "odd"> Odd </button>
<button id = "even"> Even </button>
<button id = "formula"> :nth-child(4n+4) </button>
<script>
$(document).ready(function(){
    $("#n").click(function () {
    $("li:nth-child(7)").css("background-color", "yellow");
    });

$("#odd").click(function () {
$("li").css("background-color", "white");
    $("li:nth-child(odd)").css("background-color", "orange");
    });

$("#even").click(function () {
$("li").css("background-color", "white");
    $("li:nth-child(even)").css("background-color", "lightgreen");
    });

$("#formula").click(function () {
    $("li").css("background-color", "white");
$("li:nth-child(4n+4)").css("background-color", "lightblue");

    });

});
</script>
</body>
</html>
输出:

Welcome to the lidihuo.com

It is an example of using the jQuery :nth-child selector.

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

Click the following buttons to see the effect.

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4