Implementing jQuery Cookie Plugin

£可爱£侵袭症+ 提交于 2019-12-23 03:43:06

问题


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: '/' });
}


来源:https://stackoverflow.com/questions/1990299/implementing-jquery-cookie-plugin

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