Implementing jQuery Cookie Plugin

2019-05-30 05:52发布

问题:

How would I implement the jQuery Cookie Plugin into this snippet of jQuery, so it saves the open/closed state of the toggles upon leaving the page?

$(document).ready(function() {
  $('a.toggle').click(function() { 
   var id = $(this).attr('name');
   $('#module' + id).slideToggle('fast');
   $('a.toggle[name='+id+']').toggle();
   return false; 
  });
});

回答1:

This should save the state as long as they don't close the tab/window during the animation. If you're worried about that, it wouldn't be hard to fix.

$(function() {
    $('a.toggle').click(function() { 
        var id = $(this).attr('name');
        $('#module' + id).slideToggle(
            'fast',
            function() { set_cookie(this, 'module_' + id); }
        );
        $('a.toggle[name='+id+']').toggle(
            'normal',  // speed required to use callback
            function() { set_cookie(this, 'link_' + id}
        );
        return false; 
  });
});

function set_cookie(target, name) {
    var is_displayed = $(target).css('display') != 'none';
    $.cookie(name, is_displayed, { expires: 30, path: '/' });
}