用Jquery烘烤一个cookie

时间:2011-05-22 09:44:18

标签: javascript jquery

有人可以告诉我为什么这不起作用:

$(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();
    };
});
  

jsFiddle Example

我没有看到任何错误,但在刷新时,面板不会保持其状态(无论是打开还是关闭)。它只是返回到关闭的默认状态。我正在使用插件来获取cookie。

2 个答案:

答案 0 :(得分:2)

插件行为按预期工作。问题是你误解了click()事件是如何运作的。

你已经给它了两个函数参数,假设它们将被调用,或者设置cookie值。由于只调用了第二种方法,因此您的状态始终为expanded

此外,您已使用CSS在面板上设置display: none;,这意味着即使设置了正确的状态,它也不会展开。因为在你的JS中,你只检查它是否已折叠并隐藏它。

一旦解决了这些问题,它就会按预期工作。这是更新的代码。

$(document).ready(function() {
    $("#cookie").text("expanded");

    $(".btn-slide").click(function() {
        $("#panel").slideToggle("slow");
        var state = ($.cookie('panel') != 'collapsed') ? 'collapsed' : 'expanded';
        $.cookie('panel', state);
        $("#cookie").text("collapsed");
    });

    var panel = $.cookie('panel');

    if (!panel) {
        $.cookie('panel', 'expanded');
    }

    if (panel == 'collapsed') {
        $("#panel").hide();
    } else {
        $("#panel").slideDown();
    };
});

这是小提琴:http://jsfiddle.net/RJMhT/157/

请记住,我没有设置默认值,因此对于初始加载,它将被展开。一旦你真正改变了状态,它就会记住它。

答案 1 :(得分:2)

HI!

对我来说问题非常明确!

工作前:

$(document).ready(function() {

    // default:
    $("#panel").hide();
    $('#cookie').text('collapsed');

    // if cookie exist:
    if ($.cookie('panel') == 'open') {
        $('#panel').show();
        $('.slide').addClass('expanded');
        $('#cookie').text('expanded');
    }

    $(".slide").click(function() {
        $(this).toggleClass('expanded'); // toggle class
        if ($(this).hasClass('expanded')) { // now we check what happend:
            $.cookie('panel', 'open', {expires: 1} ); //create cookie if .expanded is added to button
            $('#cookie').text('expanded');
        }
        else {
            $.cookie('panel', null, {expires: 1} ); // else: delete cookie
            $('#cookie').text('collapsed');
        };
        $(this).prev('#panel').slideToggle(800);
    });
});

这是一个 JSFiddle DEMO

相关问题