0

我已经创建了一个选项卡式网页,当我刷新网页时,我需要进入选定的选项卡...

我试过但没有成功..

小提琴...

$(document).ready(function(){

    // When a link is clicked
    $("a.tab").click(function () {


        // switch all tabs off
        $(".active").removeClass("active");

        // switch this tab on
        $(this).addClass("active");

        // slide all content up
        $(".content").slideUp();

        // slide this content up
        var content_show = $(this).attr("title");
        $("#"+content_show).slideDown();
    });
});
4

2 回答 2

1

看看这个:-

现在我将偏好存储在localstorage.

有关 DOM 存储选项,请参阅 Ref。但是在您的情况下,cookie 可能是一个安全的选择,或者将其存储在服务器中。

演示

存储逻辑

 if (localStorage.activeTab) {//see if a tab has been stored in the localStorage

    $('.active').removeClass('active');
    $(".tabs li:nth-child(" + (parseInt(localStorage.activeTab, 10) + 1) + ")  a.tab").addClass('active'); //Select that tab based on preference.
   }


localStorage.activeTab = $(this).parent().index(); //Store the tab in the storage.

完整脚本

$(document).ready(function () {


    if (localStorage.activeTab) {//see if a tab has been stored in the localStorage

        $('.active').removeClass('active');
        $(".tabs li:nth-child(" + (parseInt(localStorage.activeTab, 10) + 1) + ")  a.tab").addClass('active'); //Select that tab based on preference.
    }
    // When a link is clicked
    $("a.tab").click(function () {


        // switch all tabs off
        $(".active").removeClass("active");

        // switch this tab on
        $(this).addClass("active");
        localStorage.activeTab = $(this).parent().index(); //Store the tab in the storage.
        // slide all content up
        $(".content").slideUp();

        // slide this content up
        var content_show = $(this).attr("title");
        $("#" + content_show).slideDown();
    });
});
于 2013-05-06T17:50:39.883 回答
1

通过使用来自https://github.com/carhartl/jquery-cookie的 cookie 插件

var prevActiveTab = $.cookie("activeTabIndex");

$("a.tab").removeClass("active");
var $oldActive = $("a.tab").eq(prevActiveTab).addClass("active");
$(".content").slideUp();
var content_show = $oldActive.attr("title");
$("#"+content_show).slideDown();

// When a link is clicked
$("a.tab").click(function () {

$.cookie("activeTabIndex",$("a.tab").index($(this)));
// switch all tabs off
$(".active").removeClass("active");

// switch this tab on
$(this).addClass("active");

// slide all content up
$(".content").slideUp();

// slide this content up
var content_show = $(this).attr("title");
$("#"+content_show).slideDown();

});

这里做了什么,当标签被改变时,cookie被修改index为活动标签元素。在页面刷新时,获取该索引并将类设置为active并删除其他类。

更新 由于需要存储的数据量非常少,您可以选择使用 cookie 方法而不是 localstorage。如果您想针对 IE < 8,浏览器兼容性也是一个问题。

于 2013-05-06T17:54:40.780 回答