jquery - 显示带有 url 的选项卡

标签 jquery

我编写了一个代码,可以将李的类更改为事件状态并在单击时显示正确的内容,但我也希望能够将访问者链接到示例: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/

相关文章:

javascript - 标题 div 在滚动时保持不变,但向上移动到下一个,但保持在 nabber 菜单下方

javascript - 为什么使用 textContent 进行 linkify 不起作用

javascript - iPhone/iPad 悬停事件 jQuery

javascript - 将 JavaScript 数据添加到页面时什么更有效 : creating new elements or populating existing ones?

php - 不将 ajax 查询中的 html 选择数据保存到 session 中

javascript - jQuery find() 方法不适用于一个(!)类

javascript - 是否有 jQuery/sizzle 的替代方案支持 textNodes 作为选择器中的一等公民?

jquery - jqgrid json加载行号为负

jquery - 为自定义非 RESTful 服务器覆盖 Backbone 中的持久性方法

php - 如何将自定义 css 和 js 文件添加到 wordpress 的管理区域