Toggle and preserve state with jquery and cookies

2019-07-11 14:07发布

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>

1条回答
戒情不戒烟
2楼-- · 2019-07-11 14:52

This guy:

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

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");
    });
 });
查看更多
登录 后发表回答