八、节点遍历

一、本课目标

  • 掌握jQuery的节点遍历

二、节点遍历

  • 遍历子元素
  • 遍历同辈元素
  • 遍历前辈元素
  • 其他遍历方法

2.1遍历子元素

children()方法可以用来获取元素的所有子元素。

$(selector).children([expr]);

2.2遍历同辈元素

jQuery可以获取紧邻其后、紧邻其前和位于该元素前与后的所有同辈元素

image.png

示例代码:
html文件:



 
  
  
  
  
  
  仿冬奥列表内容
     
 
 
    

水果

  • 西瓜
  • 苹果
  • 香蕉
  • 火龙果
  • 柠檬

css文件:

*{padding:0;margin:0;}
html,body{font-family:"微软雅黑";}
.contain{width:320px;margin:5px auto; border: 1px solid #2a65ba;}
.gameList{list-style:none;}
.gameList li{padding-left:15px;line-height:40px; height:40px;font-size:12px;color:#000;border-bottom:1px #aaaaaa dashed;}
h2{font-size:16px;padding-left:20px;line-height:40px;}

js文件:

$(document).ready(function () {
    // 获取所有的子元素并输出长度
    var $section = $(".gameList").children();
    //alert($section.length);
    // 获取之前、之后和所有的同辈元素
    $(".gameList li:eq(2)").next().css("background", "red");
    $(".gameList li:eq(2)").prev().css("background", "green");
    $(".gameList li:eq(2)").siblings().css("background", "yellow");
})

2.3遍历前辈元素

jQuery中可以遍历前辈元素

parent():获取元素的父级元素
parents():获取元素的祖先元素

示例代码:

$(document).ready(function () {
    // 获取li标签的父元素
    $("ul li:nth-of-type(1)").parent().css("background", "red");
    //获取li元素的祖先元素
    $("ul li:eq(1)").parents().css("background", "yellow");
})

2.4each()方法

each():规定为每个匹配元素规定运行的函数(相当于是个循环)

$(selector).each(function(){index, element});
image.png

示例代码:

$(document).ready(function () {
   //当点击h2标题的时候,获取每一个li元素的内容追加到div标签后
    $("h2").click(function () {
        $("li").each(function(){
            var str = $(this).text() + "
"; $("div").append(str); }) }) })

2.5end()方法

end():结束当前链条中的最近的筛选操作,并将匹配元素集还原为之前的状态。
示例代码:

$(document).ready(function () {
    // first方法获取元素集合中的第一个元素
    // last方法用于获取最后一个元素
    $("ul li").first().css("background", "red").end().last().css("background", "green");
})

2.6CSS-DOM操作

除css()外,还有获取和设置元素高度、宽度等的样式操作方法。


image.png

示例代码:




    
随鼠标滚动的广告图片




三、总结

image.png

你可能感兴趣的:(八、节点遍历)