2013-04-23 18 views
0

我有一些像這樣的鏈接的頁面: test1.htmlHREF到頁面+變化類名的.js文件一次

<div> 
<a href="test2.html">Go to TAB1</a> 
<a href="test2.html">Go to TAB2</a> 
</div> 

的第二頁是用標籤頁: test2.html

<div id="tab1" class="active-content">  
    <p>Hello this is the first TAB</p> 
</div> 
<div id="tab2" class="content"> 
    <p>Hello this is the second TAB</p> 
</div> 

我需要做的是,當我點擊Go to TAB2 HREF,更改爲test2.html頁面,改變它的DIV CL屁股,所以他們看起來像這樣:(爲了顯示頁面加載時的第二個選項卡)。

<div id="tab1" class="content">  
    <p>Hello this is the first TAB</p> 
</div> 
<div id="tab2" class="active-content"> 
    <p>Hello this is the second TAB</p> 
</div> 

我試圖使用javascript href="javascript:tab()"但我不能同時做兩件事情。頁面更改爲test2.html,但在頁面加載之前運行代碼。

function tab(){ 
    window.location.href='test2.html'; 
    var element = document.getElementById("tab1"); 
    element.className="content"; 
    var element = document.getElementById("tab2"); 
    element.className="active-content"; 
} 

我嘗試使用setTimeoutonload方法,但一無所獲。 我需要更改爲test2.html並更改爲第二個選項卡,只需單擊href,我該如何執行此操作?

+1

嘗試使用類似'test2.html#tab1'的URL,並讓你的'onload'方法檢查'document.location.hash'。 – Barmar 2013-04-23 09:27:29

+0

我嘗試過使用'test2.html#tab2',但是轉到了#tab1,這是一個墮落者。我不能把'onload加到#tab2'上,因爲我也想用第一個鏈接出現tab1 – Flowen 2013-04-23 09:29:11

回答

0

添加一個片段:

<a href="test2.html#tab2">Go to TAB2</a> 

然後在test2.html有這個JavaScript:

var tabnum = location.hash.replace('#', ''); 
if (tabnum) { 
    document.getElementById(tabnum).className = "active-content"; 
} 
0

首先,你需要使用URL發送一些數據。這將被test2頁面拾取,並可以採取行動。

另一頁上的一個錨的引用由哈希定義:

test2.html#tab1 

這通常會滾動頁面的錨,但你可以寫一個小的JavaScript解析URL爲「# 「並更改相關的類:

var url_raw=window.location.href; 

//Split the string at the #, and take the second part 
var layer_to_change=url.split("#")[1]; 

//Set the class of the needed layer 
document.getElementById(layer_to_change).className="active-content"; 

這將駐留在onload事件處理程序中。

相關問題