2013-07-18 72 views
0

我在互聯網上發現了jQuery中的選項卡系統,但是製作它(並授權使用它)的人不再可用於聯繫人,所以這就是爲什麼我在這裏問這個問題的原因。通過URL訪問特定選項卡

這是管理不同選項卡的JavaScript代碼。

window.onload=function() {​ 



// get tab container 
    var container = document.getElementById("tabContainer"); 
    if (document.location.hash.length) { 
     $('.tabs ul li a[href^="' + document.location.hash + '"]').click(); 
    } 
// set current tab 
var navitem = container.querySelector(".tabs ul li"); 
//store which tab we are on 
var ident = navitem.id.split("_")[1]; 
navitem.parentNode.setAttribute("data-current",ident); 
//set current tab with class of activetabheader 
navitem.setAttribute("class","tabActiveHeader"); 

//hide two tab contents we don't need 
var pages = container.querySelectorAll(".tabpage"); 
for (var i = 1; i < pages.length; i++) { 
    pages[i].style.display="none"; 
} 

//this adds click event to tabs 
var tabs = container.querySelectorAll(".tabs ul li"); 
for (var i = 0; i < tabs.length; i++) { 
    tabs[i].onclick=displayPage; 
} 
} 

// on click of one of tabs 
function displayPage() { 
    var current = this.parentNode.getAttribute("data-current"); 
    //remove class of activetabheader and hide old contents 
    document.getElementById("tabHeader_" + current).removeAttribute("class"); 
    document.getElementById("tabpage_" + current).style.display="none"; 

    var ident = this.id.split("_")[1]; 
    //add class of activetabheader to new active tab and show contents 
    this.setAttribute("class","tabActiveHeader"); 
    document.getElementById("tabpage_" + ident).style.display="block"; 
    this.parentNode.setAttribute("data-current",ident); 
} 

這是HTML:

  <div class="tabs"> 
      <ul> 
       <li id="tabHeader_1">Les listes</li> 
       <li id="tabHeader_2">Les membres</li> 
      </ul> 
     </div> 
<div class="tabscontent"> 
      <div class="tabpage" id="tabpage_1"> 
       <h2>Les listes</h2> 
       <p>Pellentesque habitant morbi tristique senectus...</p> 
      </div> 
      <div class="tabpage" id="tabpage_2"> 
       </div> 

默認的JavaScript加載第一個選項卡(tabHeader_1,tabpage_1)。我想要的是,如果我在例如example.com/page.php#tabpage_2中輸入example,它會自動加載第二個選項卡。

非常感謝您的幫助。

回答

0

document.location.hash返回帶號碼符號(#hash)的散列。
您也不能使用.tabs ul li a作爲選擇器,因爲li內部沒有a標記。

嘗試使用:

var hash = document.location.hash.substr(1); // skip 1 character (the number sign) 
$('.tabs ul li[id^="' + hash + '"]').click(); 

而且,這個腳本是不是in jQuery。它只在整個腳本中使用1個jQuery函數。我會考慮這個比jQuery更純的JavaScript。

+0

它工作完美。謝謝。 –

相關問題