jQuery教程09-子元素筛选选择器
2018-04-02 08:33
507 查看
jQuery选择器之子元素筛选选择器
子元素筛选选择器不常使用,其筛选规则比起其它的选择器稍微要复杂点子元素筛选选择器描述表:
注意:
:first只匹配一个单独的元素,但是:first-child选择器可以匹配多个:即为每个父级元素匹配第一个子元素。这相当于:nth-child(1)
:last 只匹配一个单独的元素, :last-child 选择器可以匹配多个元素:即,为每个父级元素匹配最后一个子元素
如果子元素只有一个的话,:first-child与:last-child是同一个
:only-child匹配某个元素是父元素中唯一的子元素,就是说当前子元素是父元素中唯一的元素,则匹配
jQuery实现:nth-child(n)是严格来自CSS规范,所以n值是“索引”,也就是说,从1开始计数,:nth-child(index)从1开始的,而eq(index)是从0开始的
nth-child(n) 与 :nth-last-child(n) 的区别前者是从前往后计算,后者从后往前计算
代码示例:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <title></title> <link rel="stylesheet" href="imooc.css" 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>
相关文章推荐
- jQuery选择器之子元素筛选选择器
- jQuery选择器之子元素筛选选择器
- jQuery教程06-基本筛选选择器
- jQuery教程07-内容筛选选择器
- jQuery教程08-属性筛选选择器
- 献给和我合作的过得前端童靴们:jquery源码分析--核心函数(创建选择器筛选document元素)
- JQuery选择器——子元素筛选选择器和表单元素选择器
- Jquery如何选取元素及其所有子元素?jquery选择器大全
- jquery 选择器(name,属性,元素)大全
- jQuery学习记录(三):使用jQuery选择器获取网页中的元素、对象及子对象
- jQuery选择器之内容筛选选择器
- jQuery-1.9.1源码分析系列(二)jQuery选择器续2——筛选
- jQuery基本筛选选择器(一)
- JQuery里面的几种选择器——查找满足条件的元素$("#控件ID")
- jQuery 教程 (二) 万能的选择器1 .NET
- .jQuery文档分析3-jQuery元素筛选
- JQuery 教程之选择器
- 使用jQuery筛选排除元素以修改指定标签的属性
- jQuery入门30分钟--使用jQuery强大的选择器引擎从DOM中选取元素
- jquery 用于选择多个元素的多选择器