① $(this).next(); 获取的是当前元素的下一个兄弟元素
②$(this).nextAll(); 获取的是当前元素的后面的所有的兄弟元素
③$(this).prev(); 获取的是当前元素的前一个兄弟元素
④$(this).prevAll(); 获取的是当前元素的前面的所有的兄弟元素
⑤$(this).siblings(); 获取的是当前元素的所有的兄弟元素(自己除外)
案例练习:
需求分析:鼠标进入文字,当前文字背景变红色,当点击时候,当前文字前面文字背景颜色变为黄色,后面文字背景颜色变为蓝色,当鼠标移出时,所有背景颜色取消
效果:
代码如下:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <style> 7 ul { 8 list-style-type: none; 9 200px; 10 margin: 100px auto; 11 } 12 13 ul li { 14 margin-top: 10px; 15 cursor: pointer; 16 text-align: center; 17 font-size: 20px; 18 } 19 </style> 20 <script src="js/jquery-1.12.2.js" type="text/javascript" charset="utf-8"></script> 21 <script> 22 //获取ul中所有的li,有鼠标进入事件,鼠标离开事件,点击事件 23 // $(function () { 24 // //获取ul->li 25 // $("ul>li").mouseenter(function () { 26 // $(this).css("backgroundColor","red").siblings().css("backgroundColor",""); 27 // }).mouseleave(function () { 28 // $(this).css("backgroundColor","").siblings().css("backgroundColor",""); 29 // }).click(function () { 30 // //当前元素前面的所有兄弟元素背景颜色为黄色 31 // //$(this).prevAll().css("backgroundColor","yellow"); 32 // //当前元素后面的所有兄弟元素背景颜色为蓝色 33 // //$(this).nextAll().css("backgroundColor","blue"); 34 // 35 // //链式编程代码 36 // //断链:对象调用方法,返回的不是当前的对象,再调用方法,调用不了, 37 // //解决断链--->恢复到断链之前的一个效果--修复断链 38 // //.end()方法恢复到断链之前的效果 39 // $(this).prevAll().css("backgroundColor","yellow").end().nextAll().css("backgroundColor","blue"); 40 // }); 41 // }); 42 43 $(function(){ 44 //链式编程 鼠标进入--鼠标点击--鼠标移出 45 //$("ul>li").mouseover().click().mouseout(); 46 $("ul>li").mouseover(function(){ 47 $(this).css("backgroundColor","red").siblings("li").css("backgroundColor",""); 48 }).click(function(){ 49 $(this).prevAll().css("backgroundColor","yellow"); 50 $(this).nextAll().css("backgroundColor","blue"); 51 }).mouseout(function(){ 52 $("ul>li").css("backgroundColor",""); 53 }); 54 }); 55 </script> 56 </head> 57 <body> 58 <ul> 59 <li>青岛啤酒(TsingTao)</li> 60 <li>瓦伦丁(Wurenbacher)</li> 61 <li>雪花(SNOW)</li> 62 <li>奥丁格教士(Franziskaner)</li> 63 <li>科罗娜喜力柏龙(Paulaner)</li> 64 <li>嘉士伯Kaiserdom</li> 65 <li>罗斯福(Rochefort)</li> 66 <li>粉象(Delirium)</li> 67 <li>爱士堡(Eichbaum)</li> 68 <li>哈尔滨牌蓝带</li> 69 </ul> 70 71 </body> 72 </html>
注意: 上述代码第49、50行可以压缩成一行,这样就引入了一个新的方法
end();作用是恢复短链。
原来两行代码:
$(this).prevAll().css("backgroundColor","yellow");
$(this).nextAll().css("backgroundColor","blue");
修改后代码:
$(this).prevAll().css("backgroundColor","yellow").end().nextAll().css("backgroundColor","blue");