欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

jQuery子元素选择器详解

程序员文章站 2022-04-25 23:48:02
...
本文主要和大家详细介绍了jQuery选择器之子元素选择器,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能帮助到大家。

jQuery子元素选择器详解


<!DOCTYPE html>
<html>

<head>
  <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
  <title></title>
  <link rel="stylesheet" href="imooc.css" rel="external nofollow" type="text/css">
  <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script>
</head>

<body>
  <h2>子元素筛选选择器</h2>
  <h3>:first-child、:last-child、:only-child</h3>
  <p class="left first-p">
    <p class="p">
      <a>:first-child</a>
      <a>第二个元素</a>
      <a>:last-child</a>
    </p>
    <p class="p">
      <a>:first-child</a>
    </p>
    <p class="p">
      <a>:first-child</a>
      <a>第二个元素</a>
      <a>:last-child</a>
    </p>
  </p>

  <script type="text/javascript">
    //查找class="first-p"下的第一个a元素
    //针对所有父级下的第一个
    $(".first-p a:first-child").css("color", "#CD00CD");
  </script>

  <script type="text/javascript">
    //查找class="first-p"下的最后一个a元素
    //针对所有父级下的最后一个
    //如果只有一个元素的话,last也是第一个元素
    $(".first-p a:last-child").css("color", "red");
  </script>

  <script type="text/javascript">
    //查找class="first-p"下的只有一个子元素的a元素
    $(".first-p a:only-child").css("color", "blue");
  </script>


  <h3>:nth-child、:nth-last-child</h3>
  <p class="left last-p">
    <p class="p">
      <a>:first-child</a>
      <a>第二个元素</a>
      <a>第三个元素</a>
      <a>:last-child</a>
    </p>
    <p class="p">
      <a>:first-child</a>
      <a>第二个元素</a>
    </p>
    <p class="p">
      <a>:first-child</a>
      <a>第二个元素</a>
      <a>第三个元素</a>
      <a>:last-child</a>
    </p>
  </p>

  <script type="text/javascript">
    //查找class="last-p"下的第二个a元素
    $(".last-p a:nth-child(2)").css("color", "#CD00CD");
  </script>

  <script type="text/javascript">
    //查找class="last-p"下的倒数第二个a元素
    $(".last-p a:nth-last-child(2)").css("color", "red");
  </script>

</body>

</html>

相关推荐:

CSS的子元素选择器用法详细介绍

以上就是jQuery子元素选择器详解的详细内容,更多请关注其它相关文章!