jQuery子元素选择器 jQuery选择器之子元素选择器详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

jQuery子元素选择器 jQuery选择器之子元素选择器详解

喵嘻嘻   2021-03-29 我要评论
想了解jQuery选择器之子元素选择器详解的相关内容吗,喵嘻嘻在本文为您仔细讲解jQuery子元素选择器的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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>
  <div class="left first-div">
    <div class="div">
      <a>:first-child</a>
      <a>第二个元素</a>
      <a>:last-child</a>
    </div>
    <div class="div">
      <a>:first-child</a>
    </div>
    <div class="div">
      <a>:first-child</a>
      <a>第二个元素</a>
      <a>:last-child</a>
    </div>
  </div>

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

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

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


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

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

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

</body>

</html>

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们