2011-03-04 61 views
0

我用jQuery创建了一个带标签的界面来显示/隐藏内容。JavaScript选项卡式界面 - 如何链接并为选项卡添加书签?

我希望能够链接到特定的选项卡,并允许用户为他们所在的当前选项卡添加书签。

由于我使用每个包含div的ID,我可以通过从click事件中删除return false;来实现此目的,但这会导致页面跳转到包含该标签的div。

有没有确保URL包含地址的#部分但防止页面跳过的方法?还有另一种解决这个问题的方法,我还没有遇到过吗?

//Get all containers with tab content 
var tabContainers = $("div.tab"); 

//Get value of # from URL 
if (window.location.hash) { 

    //if there's a # display the relevant tab 
    $(tabContainers).hide().filter(window.location.hash).show(); 

} else { 
    //Show the first tab 
    $(tabContainers).hide().filter(":first").show();  
} 


$("ul#tabNav a").click(function() { 

    //Hide all tab content then display the current 
    $(tabContainers).hide().filter(this.hash).show(); 

    //prevent page from skipping but also prevents # from appearing in address bar 
    return false; 

}); 





<div id="tabNavContainer"> 
    <ul id="tabNav"> 
     <li id="tab1"> <a href="#a">Course essentials</a> </li> 
     <li id="tab2"> <a href="#b">Course details</a> </li> 
     <li id="tab3"> <a href="#c">Next steps</a> </li> 
    </ul> 
</div> 
<div class="tab" id="a"> 
    <h3>TAB A</h3> 
</div> 
<div class="tab" id="b"> 
    <h3>TAB B</h3> 
</div> 
<div class="tab" id="c"> 
    <h3>TAB C</h3> 
</div> 

任何帮助,非常感谢。

回答

0

您可以设置window.location.hash以及阅读它:

$("ul#tabNav a").click(function() { 

    //Hide all tab content then display the current 
    $(tabContainers).hide().filter(this.hash).show(); 

    window.location.hash = this.hash; 

    //prevent page from skipping but also prevents # from appearing in address bar 
    return false; 

}); 

注意,这将增加一个页面到浏览器历史记录,允许用户使用前进和后退按钮来更改哈希值。理想情况下,你也应该看看如何处理。

+0

谢谢,但这与删除返回false具有相同的效果。当链接被点击时,页面跳过。 – 2011-03-04 13:51:32

+0

对不起,没有正确测试。 – roryf 2011-03-04 14:03:07

相关问题