您好,欢迎访问一九零五行业门户网

jQuery如何获取兄弟元素?(代码示例)

本篇文章给大家带来的内容是关于jquery如何获取兄弟元素?(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
① $(this).next();        获取的是当前元素的下一个兄弟元素
②$(this).nextall();       获取的是当前元素的后面的所有的兄弟元素
③$(this).prev();           获取的是当前元素的前一个兄弟元素
④$(this).prevall();       获取的是当前元素的前面的所有的兄弟元素
⑤$(this).siblings();      获取的是当前元素的所有的兄弟元素(自己除外)
案例练习:
需求分析:鼠标进入文字,当前文字背景变红色,当点击时候,当前文字前面文字背景颜色变为黄色,后面文字背景颜色变为蓝色,当鼠标移出时,所有背景颜色取消
效果:
代码如下:
<!doctype html><html><head> <meta charset="utf-8"> <title>title</title> <style> ul { list-style-type: none; width: 200px; margin: 100px auto; } ul li { margin-top: 10px; cursor: pointer; text-align: center; font-size: 20px; } </style> <script src="js/jquery-1.12.2.js" type="text/javascript" charset="utf-8"></script> <script> //获取ul中所有的li,有鼠标进入事件,鼠标离开事件,点击事件// $(function () {// //获取ul->li// $("ul>li").mouseenter(function () {// $(this).css("backgroundcolor","red").siblings().css("backgroundcolor","");// }).mouseleave(function () {// $(this).css("backgroundcolor","").siblings().css("backgroundcolor","");// }).click(function () {// //当前元素前面的所有兄弟元素背景颜色为黄色// //$(this).prevall().css("backgroundcolor","yellow");// //当前元素后面的所有兄弟元素背景颜色为蓝色// //$(this).nextall().css("backgroundcolor","blue");// // //链式编程代码// //断链:对象调用方法,返回的不是当前的对象,再调用方法,调用不了,// //解决断链--->恢复到断链之前的一个效果--修复断链// //.end()方法恢复到断链之前的效果// $(this).prevall().css("backgroundcolor","yellow").end().nextall().css("backgroundcolor","blue");// });// }); $(function(){ //链式编程 鼠标进入--鼠标点击--鼠标移出 //$("ul>li").mouseover().click().mouseout(); $("ul>li").mouseover(function(){ $(this).css("backgroundcolor","red").siblings("li").css("backgroundcolor",""); }).click(function(){ $(this).prevall().css("backgroundcolor","yellow"); $(this).nextall().css("backgroundcolor","blue"); }).mouseout(function(){ $("ul>li").css("backgroundcolor",""); }); }); </script></head><body><ul> <li>青岛啤酒(tsingtao)</li> <li>瓦伦丁(wurenbacher)</li> <li>雪花(snow)</li> <li>奥丁格教士(franziskaner)</li> <li>科罗娜喜力柏龙(paulaner)</li> <li>嘉士伯kaiserdom</li> <li>罗斯福(rochefort)</li> <li>粉象(delirium)</li> <li>爱士堡(eichbaum)</li> <li>哈尔滨牌蓝带</li></ul></body></html>
注意: 上述代码第49、50行可以压缩成一行,这样就引入了一个新的方法
end();作用是恢复短链。
原来两行代码:
$(this).prevall().css("backgroundcolor","yellow");$(this).nextall().css("backgroundcolor","blue");
修改后代码:
$(this).prevall().css("backgroundcolor","yellow").end().nextall().css("backgroundcolor","blue");
以上就是jquery如何获取兄弟元素?(代码示例)的详细内容。
其它类似信息

推荐信息