使用jq寫選項卡,告別了繁瑣的回圈以及命名規范
基本原理:
1.當某一個btn被選中時,將這個btn的背景顏色設為橘色,其余兄弟btn背景顏色設為空(none)
2.如果子div與btn的索引相同,就將這個div顯示而其他兄弟div隱藏
1).css函式引數2的回呼函式方法;
2).原生get方法再轉jq物件 再進行設定的方法
3).當前div使用show()方法,其余兄弟div使用hide()方法
關鍵字:get() siblings() show() hide() css()
html頁:
4個btn,4個div
<div id="wrap"> <button>btn1</button> <button>btn2</button> <button>btn3</button> <button>btn4</button> <div>1</div> <div>2</div> <div>3</div> <div>4</div> </div>
css頁:
大盒子當前無樣式,在實際開發中需要指定其寬高;第一個btn背景色為橘黃色;第一個子項div顯示,其余兄弟div隱藏
#wrap div { width: 300px; height: 200px; border: 1px solid red; display: none; } #wrap div:nth-of-type(1) { display: block; /* 第一個子項div顯示 */ } #wrap button:nth-of-type(1) { background: orange; /* 第一個btn背景色為橘黃色; */ }
jquery頁:
1)首先給btn系結事件
$("#wrap button").click(function() { //當btn被點擊后發生的事件}) 關鍵字: click();
2) 當btn被點擊時,設定當前選中btn顏色為橘色,并且將其他兄弟btn背景色為空:
$(this).css("background", "orange").siblings("button").css("background", "none")關鍵字: $(this); css(); siblings()
3) 宣告一個變數,這個變數保存了被選中的btn的下標
var $index = $(this).index();
關鍵字:$index; $(this);index();
// 1:找到所有的子div,并且設定css樣式,如果某個div的索引與btn的索引相同,就讓他顯示 $("#wrap div").css("display", function(i) { if (i == $index) { return "block"; } return "none"; })
關鍵字:css() ; "display" ; i == $index;
b:通過get()方法將子div的索引與當前btn的索引系結,然后再將這個索引轉變成jq物件,再使用jq方法將對應div顯示
$($("#wrap div").get($(this).index())).css("display", "block").siblings("div").css("display", "none")由于get方法是js原生方法,所以應將其轉成jq物件才能使用jq方法
關鍵字: $() ; $(this).index; get();css();siblings()
c:通過當前btn的索引系結div的索引,進而將這個索引對應的div顯示show(),并將其余的div兄弟元素隱藏hide()
$("#wrap div").eq($(this).index()).show().siblings("div").hide();關鍵字:eq();$(this).index();show();hide()
這樣,就完成了使用jQuery方法實作選項卡,
以上,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/36819.html
標籤:jQuery
上一篇:Javascript 日歷插件
下一篇:按鍵批量操作示例
