使用 Jquery 烘焙 cookie
有人可以告诉我为什么这不起作用:
$(document).ready(function() {
$("#cookie").text("expanded");
//panel toggle
$(".btn-slide").click(function() {
$("#panel").slideToggle("slow");
//set the name and value of the cookie
$.cookie('panel', 'collapsed');
$("#cookie").text("collapsed");
}, function() {
$("#panel").slideDown("slow");
//set the name and value of the cookie
$.cookie('panel', 'expanded');
$("#cookie").text("expanded");
});
// cookie
var panel = $.cookie('panel');
// Set the user's selection for the state
if (panel == 'collapsed') {
$("#panel").hide();
};
});
我没有看到任何错误,但在刷新时面板不保持其状态(无论是打开还是关闭)。它只是返回到关闭的默认状态。我正在使用 cookie 插件。
Can someone tell me why this doesn't work:
$(document).ready(function() {
$("#cookie").text("expanded");
//panel toggle
$(".btn-slide").click(function() {
$("#panel").slideToggle("slow");
//set the name and value of the cookie
$.cookie('panel', 'collapsed');
$("#cookie").text("collapsed");
}, function() {
$("#panel").slideDown("slow");
//set the name and value of the cookie
$.cookie('panel', 'expanded');
$("#cookie").text("expanded");
});
// cookie
var panel = $.cookie('panel');
// Set the user's selection for the state
if (panel == 'collapsed') {
$("#panel").hide();
};
});
I don't see anyting wrong, but on refresh the panel doesn't keep it's state (whether open or closed). It just returns to the closed default state. I'm using a plugin for the cookies.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
插件行为按预期工作。问题是您误解了 click() 事件的工作原理。
您已经给了它两个函数参数,假设它们将被交替调用来设置 cookie 值。由于只调用了第二个方法,因此您的状态将始终
扩展
。此外,您还使用 CSS 在面板上设置了
display: none;
,这意味着即使设置了正确的状态,它也不会展开。因为在你的JS中,你只检查它是否折叠并隐藏它。一旦解决了这些问题,它就会按预期工作。这是更新后的代码。
这是小提琴: http://jsfiddle.net/RJMhT/157/
请记住,我尚未设置默认值,因此对于初始加载,它将被扩展。一旦你真正改变了状态,它就会记住它。
The plugin behavior works as expected. The problem is that you've misunderstood how the click() event works.
You've given it two function arguments assuming that they will be called in alternatively to set the cookie values. Since only the second method is ever called, your state will always be
expanded
.Also, you've set
display: none;
on the panel with your CSS, which means it won't expand even if the proper state was set. Because in your JS, you only check whether it's collapsed and hide it.It works as expected once you fix these issues. Here's the updated code.
And here's the fiddle : http://jsfiddle.net/RJMhT/157/
Keep in mind that I haven't set a default, so for the initial loads it will be expanded. And once you've actually changed the state it will remember it.
你好!
对我来说这个问题很清楚!
工作示例:
这是一个 JSFiddle 演示
HI!
Well to me the question was pretty clear!
Working Ex:
And here is a JSFiddle DEMO