本帖最后由 zhaorong 于 2017-9-18 15:41 编辑
本文实例为大家分享了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>
复制代码
以上就是本文的全部内容,希望对大家的学习有所帮助。
|