电脑疯子技术论坛|电脑极客社区

微信扫一扫 分享朋友圈

已有 2005 人浏览分享

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

[复制链接]
2005 0
本帖最后由 zhaorong 于 2017-9-18 15:41 编辑

本文实例为大家分享了jQuery子元素选择器,供大家参考,具体内容如下

2017918135005849.jpg

  1. <!DOCTYPE html>
  2. <html>

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

  9. <body>
  10.   <h2>子元素筛选选择器</h2>
  11.   <h3>:first-child、:last-child、:only-child</h3>
  12.   <div class="left first-div">
  13.     <div class="div">
  14.       <a>:first-child</a>
  15.       <a>第二个元素</a>
  16.       <a>:last-child</a>
  17.     </div>
  18.     <div class="div">
  19.       <a>:first-child</a>
  20.     </div>
  21.     <div class="div">
  22.       <a>:first-child</a>
  23.       <a>第二个元素</a>
  24.       <a>:last-child</a>
  25.     </div>
  26.   </div>

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

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

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


  42.   <h3>:nth-child、:nth-last-child</h3>
  43.   <div class="left last-div">
  44.     <div class="div">
  45.       <a>:first-child</a>
  46.       <a>第二个元素</a>
  47.       <a>第三个元素</a>
  48.       <a>:last-child</a>
  49.     </div>
  50.     <div class="div">
  51.       <a>:first-child</a>
  52.       <a>第二个元素</a>
  53.     </div>
  54.     <div class="div">
  55.       <a>:first-child</a>
  56.       <a>第二个元素</a>
  57.       <a>第三个元素</a>
  58.       <a>:last-child</a>
  59.     </div>
  60.   </div>

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

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

  69. </body>

  70. </html>
复制代码


以上就是本文的全部内容,希望对大家的学习有所帮助。



您需要登录后才可以回帖 登录 | 注册

本版积分规则

1

关注

0

粉丝

9021

主题
精彩推荐
热门资讯
网友晒图
图文推荐

Powered by Pcgho! X3.4

© 2008-2022 Pcgho Inc.