0

我有一些这样的链接页面: test1.html

<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 TAB2href 时,切换到页面test2.html并更改 div 类,使它们看起来像这样:(为了在页面加载时显示第二个 TAB)。

<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";
}

我尝试使用setTimeoutoronload方法但没有。我需要更改为 test2.html 并更改为第二个选项卡,只需单击一个 href,我该怎么做?

4

2 回答 2

1

首先,您需要使用 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 事件处理程序中。

于 2013-04-23T09:31:54.653 回答
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";
}
于 2013-04-23T09:28:02.357 回答