jq方法寫選項卡的基本原理以及三種方法


使用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方法實現選項卡。

  以上。

 

 

 

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM