Toggle and preserve state with jquery and cookies

纵饮孤独 提交于 2020-02-04 02:51:12

问题


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:


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");
    });
 });


来源:https://stackoverflow.com/questions/6124039/toggle-and-preserve-state-with-jquery-and-cookies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!