我编写了一个代码,可以将李的类更改为事件状态并在单击时显示正确的内容,但我也希望能够将访问者链接到示例:www.socal.nu/index.php#tab2 来激活选项卡2。
代码:
$(document).ready(function() {
//Default Action
$(".tab_content").hide();
$("ul.tabs li:first").addClass("active").show();
$(".tab_content:first").show();
//On Click Event
$("ul.tabs li").click(function() {
$("ul.tabs li").removeClass("active");
$(this).addClass("active");
$(".tab_content").hide();
var activeTab = $(this).find("a").attr("href");
$(activeTab).fadeIn();
return false;
});
});
编辑以包含选项卡列表的 (x)html 结构(如 OP 在 @slightlymore's answer 的评论中发布的):
<ul class="tabs">
<li><a href="#tab1">Hem</a></li>
<li><a href="#tab2">Projekt</a></li>
<li><a href="#tab3">Om SOCAL</a></li>
<li><a href="#tab4">Kontakt</a></li>
</ul>
最佳答案
要从 URL 获取选项卡,请执行以下操作:
var tab = window.location.hash;
然后您可以触发 li
的点击事件,该 a
具有正确的 href
:
var tab = window.location.hash;
// Fire click on the <li> that has the <a> with the proper 'href' attribute
$("ul.tabs li:has(a[href=" + tab + "])").click();
或者您可以重用为点击事件和初始页面加载创建的函数。
// Function that is used for click event and page load
function loadTab() {
$("ul.tabs li").removeClass("active");
$(this).addClass("active");
$(".tab_content").hide();
var activeTab = $(this).find("a").attr("href");
$(activeTab).fadeIn();
return false;
}
// set up Click Event
$("ul.tabs li").click( loadTab );
var tab = window.location.hash;
// check to see if there was a tab in the location, and if
// so, call loadTab if from the context of the proper <li>.
if( $("ul.tabs li:has(a[href=" + tab + "])").length ) {
loadTab.call($("ul.tabs li:has(a[href=" + tab + "])")[0]);
}
关于jquery - 显示带有 url 的选项卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3167206/