我有两个用jquery切换的div。我希望它们在页面重新加载时具有相同的状态,因此使用coockie。但它无论如何都被卡在其中一个div上,因为我似乎无法设置正确的coockie。怎么了?
<!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>
答案 0 :(得分:2)
这家伙:
jQuery(".nav").css("display")
似乎总是返回“阻止”..也许最好有一个显式变量来跟踪状态:
$(document).ready(function($) {
var isAbout = true;
if ($.cookie("visible") === "nav") {
// ...
isAbout = false;
}
$("#knapp").click(function () {
// ...
isAbout = !isAbout;
$.cookie("visible", isAbout ? "about" : "nav");
});
});