小編給大家分享一下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>瓦倫?。╓urenbacher)</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獲取兄弟元素的方法的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。