使用jquery和cookie切换和保留状态 [英] Toggle and preserve state with jquery and cookies

查看:137
本文介绍了使用jquery和cookie切换和保留状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个div,用jquery切换。我希望他们在页面重新加载时具有相同的状态,因此使用coockie。但它被困在一个divs,无论什么和那些,因为我不能似乎设置正确的coockie。发生了什么问题?

I have 2 divs which are toggled with jquery. I want them to have the same state when page reloads and therefore uses a coockie. But it gets stuck on one of the divs no matter what and thats because I cant seem to set the correct coockie. What's wrong?

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="jquery.cookie.js"></script>
<style type="text/css">
body {
    margin: 80px;
}
.about {
}

.nav {
display: none;
}
</style>
<title></title>
</head>
<body>
<div class="about">
This is the about text
</div>
<div class="nav" >
This is the nav text
</div>
<script type="text/javascript" >
    jQuery(document).ready(function($) {

        //check cookie when page loads
        if (jQuery.cookie("visible") === "nav") {
            jQuery(".nav").css({ display: "block" });
            jQuery(".about").css({ display: "none" });
        }

        jQuery("#knapp").click(function () {
            jQuery(".about").toggle(10);
            jQuery(".nav").toggle(10);

            if(jQuery(".nav").css("display")  === "block") {
                jQuery.cookie("visible", "nav");
            }
            else {
                jQuery.cookie("visible", "about");
            }

        //return false; //Prevent browser jump to the link anchor

        });
            });
</script>
<div id="about-nav toggle">
<a href="#" id="knapp">Nav toggle</a>
</div>

</body>
</html>


推荐答案

这家伙:

jQuery(".nav").css("display")

似乎总是返回block..也许这是一个更好的主意,有一个显式变量跟踪状态:

seems to always be returning "block".. Maybe it's a better idea to have an explicit variable for tracking the state:

$(document).ready(function($) {
    var isAbout = true;
    if ($.cookie("visible") === "nav") {
        // ...
        isAbout = false;
    }

    $("#knapp").click(function () {
        // ...
        isAbout = !isAbout;
        $.cookie("visible", isAbout ? "about" : "nav");
    });
 });

这篇关于使用jquery和cookie切换和保留状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆