2016-11-26 21 views
0

我嘗試在單擊時用其內容創建導航欄。我的代碼看起來很蹩腳。有沒有辦法縮短我的代碼?使用bootstrap選項卡及其內容的最佳方式

E.g:當房間點擊,JQuery的增加active#nav-hotel,並去除來自其他li元件active類。它還自己和其他人設置visibilitydisplay

HTML:

<ul class="nav nav-tabs"> 
       <li id="nav-hotel" role="presentation"><a href="#tab-hotel">Rooms</a></li> 
       <li id="nav-flight" role="presentation"><a href="#tab-flight">Flights</a></li> 
       <li id="nav-restaurant" role="presentation"><a href="#tab-restaurant">Restaurants</a></li> 
      </ul> 
      <div class="tab-content"> 
       <div id="tab-hotel">hotel</div> 
       <div id="tab-flight">flight</div> 
       <div id="tab-restaurant">restaurant</div> 
      </div> 

JQuery的:

$("#nav-hotel").click(function() { 
     $("#nav-hotel").toggleClass("active"); 
     $("#tab-hotel").css("display", "block"); 
     $("#tab-hotel").css("visibility", "visible"); 
     $("#nav-flight").removeClass("active"); 
     $("#tab-flight").css("display", "none"); 
     $("#tab-flight").css("visibility", "hidden"); 
     $("#nav-restaurant").removeClass("active"); 
     $("#tab-restaurant").css("display", "none"); 
     $("#tab-restaurant").css("visibility", "hidden"); 
    }); 
    $("#nav-flight").click(function() { 
     $("#nav-flight").toggleClass("active"); 
     $("#tab-flight").css("display", "block"); 
     $("#tab-flight").css("visibility", "visible"); 
     $("#nav-hotel").removeClass("active"); 
     $("#tab-hotel").css("display", "none"); 
     $("#tab-hotel").css("visibility", "hidden"); 
     $("#nav-restaurant").removeClass("active"); 
     $("#tab-restaurant").css("display", "none"); 
     $("#tab-restaurant").css("visibility", "hidden"); 
    }); 
    $("#nav-restaurant").click(function() { 
     $("#nav-restaurant").toggleClass("active"); 
     $("#tab-restaurant").css("display", "block"); 
     $("#tab-restaurant").css("visibility", "visible"); 
     $("#nav-flight").removeClass("active"); 
     $("#tab-flight").css("display", "none"); 
     $("#tab-flight").css("visibility", "hidden"); 
     $("#nav-hotel").removeClass("active"); 
     $("#tab-hotel").css("display", "none"); 
     $("#tab-hotel").css("visibility", "hidden"); 
    }); 

回答

0

您是否嘗試過使用數據切換= 「標籤」?我最近通過包含bootstrap.min.js,jquery.min.js和bootstrap.min.css並標記標籤,創建了一個沒有javascript的類似示例。

首先,數據切換標誌着你的 「一」 項目= 「標籤」

<li id="nav-hotel" role="presentation"> 
    <a href="#tab-hotel" data-toggle="tab">Rooms</a> 
</li> 

其次,標誌着你帶class = 「標籤窗格」 DIV內容項

<div id="tab-hotel" class="tab-pane">hotel</div> 

最後,添加默認啓用選項卡添加活動類到您的一個div

<div id="tab-hotel" class="tab-pane active">hotel</div> 
+0

我不知道'data-toggle'。感謝您的幫助! – Eniss

相關問題