jquery-12 折疊面板如何實現(兩種方法)
一、總結
一句話總結:1、根據點擊次數來判斷顯示還是隱藏,用data方法保證每個元素一個點擊次數;2、找到元素的下一個,然后toggle實現顯示隱藏。
1、toggle的兩種用法是什么?
有fn為事件切換
沒有fn為顯示隱藏
3 $(this).next().toggle(1000);
2、如何給標簽添加某屬性(最優)?
最優的話用data(),不會改變標簽原有的屬性
21 $('h1').data({'n':0});
3、如何根據點擊次數來判斷顯示還是隱藏,用data方法保證每個元素一個點擊次數?
data()方法
21 $('h1').data({'n':0}); 22 23 $('h1').click(function(){ 24 n=$(this).data('n'); 25 26 if(n%2==0){ 27 $(this).next().hide(1000); 28 }else{ 29 $(this).next().show(1000); 30 } 31 32 $(this).data({'n':n+1}); 33 });
4、如何找到元素的下一個,然后toggle實現顯示隱藏?
next()方法找下一個
3 $(this).next().toggle(1000);
二、折疊面板如何實現(兩種方法)
1、show和hide實現
1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>index</title> 6 <style> 7 *{ 8 font-family: 微軟雅黑; 9 } 10 </style> 11 <script src="jquery.js"></script> 12 </head> 13 <body> 14 <h1>linux</h1> 15 <p>linux is very much!linux is very much!linux is very much!linux is very much!linux is very much!linux is very much!linux is very much!linux is very much!linux is very much!linux is very much!linux is very much!linux is very much!linux is very much!linux is very much!</p> 16 17 <h1>php</h1> 18 <p>php is very much!php is very much!php is very much!php is very much!php is very much!php is very much!php is very much!php is very much!php is very much!php is very much!php is very much!php is very much!php is very much!php is very much!php is very much!php is very much!php is very much!php is very much!</p> 19 </body> 20 <script> 21 $('h1').data({'n':0}); 22 23 $('h1').click(function(){ 24 n=$(this).data('n'); 25 26 if(n%2==0){ 27 $(this).next().hide(1000); 28 }else{ 29 $(this).next().show(1000); 30 } 31 32 $(this).data({'n':n+1}); 33 }); 34 </script> 35 </html>
2、toggle實現
1 <script> 2 $('h1').click(function(){ 3 $(this).next().toggle(1000); 4 }); 5 </script>
