jQuery选项卡菜单在刷新时保持活动项目

时间:2014-02-24 09:30:43

标签: jquery html

我有这个jquery选项卡小部件。我想在点击当前活动选项卡上的某个链接时保留在此选项卡上。现在,当我点击某个链接时,将转到第一个标签。

    <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
    $(document).ready(function() {
        $("#content").find("[id^='tab']").hide();
        $("#tabs li:first").attr("id","current");
        $("#content #tab1").fadeIn();

        $('#tabs a').click(function(e) {
            e.preventDefault();
            if ($(this).closest("li").attr("id") == "current"){
                return;
            }
            else{
                $("#content").find("[id^='tab']").hide();
                $("#tabs li").attr("id","");
                $(this).parent().attr("id","current"); 
                $('#' + $(this).attr('name')).fadeIn();
            }
        });
    });
</script>

这是html

<ul id="tabs">
    <li><a href="#" name="tab1">tab1</a></li>
    <li><a href="#" name="tab2">tab2</a></li>
</ul>

<div id="content">
    <div id="tab1">
        <h2>head of tab1</h2><br/>
        // content
    </div>
    <div id="tab2">
        <h2>head of tab2</h2><br/>
        // content 2
    </div>
</div>

1 个答案:

答案 0 :(得分:0)

在结束标记<body>

之前使用此代码
<script>
$("#content").find("[id^='tab']").hide(); 
$("#tabs li:first").attr("id","current"); 
$("#content #tab1").fadeIn(); 

$('#tabs a').click(function(e) {
    e.preventDefault();
    if ($(this).closest("li").attr("id") == "current"){ 
    } else {
        $("#content").find("[id^='tab']").hide(); 
        $("#tabs li").attr("id",""); 
        $(this).parent().attr("id","current"); 
        $('#' + $(this).attr('name')).fadeIn(); 
    }

    var tab = $(this).attr("name");
    localStorage.setItem("tab", tab);
});

var currTab = localStorage.getItem("tab");
$('a[name="' + currTab + '"]').trigger("click");

注意:

浏览器对本地存储的支持不是100%,但它非常好 - 您可以期望它适用于所有现代浏览器,IE 8及更高版本以及大多数移动浏览器。

相关问题