jQuery,slideToggle - 添加Cookies以记住状态

时间:2014-09-25 16:53:17

标签: javascript jquery cookies

如何在此代码中添加Cookie以记住刷新后的状态?

jQuery的:

$("li.FOLDER A").click( function() {
    $(this).parent().find("UL:first").slideToggle("fast");
    if( $(this).parent().attr('className') == "FOLDER" ) return false;
});

HTML:

<ul>
 <li class="FOLDER"><a href="#"> open folder </a>
  <ul>
   <li>...</li>
   <li>...</li>
   <li>...</li>
  </ul>
 </li>
 <li class="FOLDER"><a href="#"> open folder </a>
  <ul>
   <li>...</li>
   <li>...</li>
   <li>...</li>
  </ul>
 </li>
</ul>

2 个答案:

答案 0 :(得分:0)

也许您可以使用本地存储(不会传输到服务器)

localStorage.setItem('isOpen', true);

var isOpen = localStorage.getItem('isOpen');

但我不太清楚你的功能如何运作 也许是这样的......

$("li.FOLDER A").click( function() {
    var isOpen = localStorage.getItem('isOpen');
    if(isOpen){
        $(this).parent().find("UL:first").slideUp("fast", function(){
            localStorage.setItem('isOpen', false);
        });

    }
    else{
        $(this).parent().find("UL:first").slideDown("fast", function(){
            localStorage.setItem('isOpen', true);
        });

    }
    if( $(this).parent().attr('className') == "FOLDER" ) return false;
})
.trigger('click');

答案 1 :(得分:0)

看一下这个插件:https://github.com/carhartl/jquery-cookie

您可能希望使用$.slideDown()$.slideUp(),以便区分是打开还是关闭元素

打开抽屉时:

$.cookie('drawer_state', 'open');

当你关闭抽屉时:

$.cookie('drawer_state', 'close');

然后在文档加载时读取抽屉状态:

$(document).ready(function(){
    if($.cookie('drawer_state') == "open"){
        $("#drawer").slideUp();
    }else{
        $("#drawer").slideDown();
    }
});

HTML:

<ul>
 <li class="FOLDER"><a href="#"> open folder </a>
  <ul id="drawer">
   <li>...</li>
   <li>...</li>
   <li>...</li>
  </ul>
 </li>
</ul>