【问题标题】:jquery and cookie statusjquery 和 cookie 状态
【发布时间】:2011-01-16 06:15:28
【问题描述】:

我想要做的是让侧边栏切换打开和关闭,这工作正常,但我也希望 cookie 在浏览网站和返回页面时记住侧边栏状态

即:如果关闭则关闭如果打开则打开:

$(document).ready(function($) {
 $('a#side').click(function(){
  $('#sidebar').toggle();
$('a#side').text($(this).text() == 'Show' ? 'Hide' : 'Show');
  $.cookie('side_cookie', 'value');
 return false;
});
if($.cookie('side_cookie')) { 
$('#sidebar').hide(); 
   } else {
$('#sidebar').show();
   }
});

上面的当前代码只记住它是否已关闭并保持关闭状态直到会话结束,因此每次返回页面时都必须将其切换为打开状态...

可以在 vbulletin.com/forum/ 上看到我尝试实现的示例,如果您关闭他们的侧边栏,然后在返回主页时浏览论坛,它仍然关闭,反之亦然。

感谢任何帮助

【问题讨论】:

    标签: jquery toggle setcookie


    【解决方案1】:

    我认为问题在于 if 条件 if($.cookie('side_cookie'))。 试试这个:

    $(document).ready(function($) {
     $('a#side').click(function(){
      $('#sidebar').toggle();
    $('a#side').text($(this).text() == 'Show' ? 'Hide' : 'Show');
      $.cookie('side_cookie', $(this).text());
     return false;
    });
    if($.cookie('side_cookie')=='Hide') { 
    $('#sidebar').hide(); 
       } else {
    $('#sidebar').show();
       }
    });
    

    【讨论】:

      【解决方案2】:

      您必须检查 cookie 的值而不是它的存在。此外,您将 cookie 的值硬编码为value。将其更改为showhide

      // when it is shown
      $.cookie('side_cookie', 'show');
      
      // when it is hidden
      
      $.cookie('side_cookie', 'hide');
      

      并检查 cookie 的值

      if($.cookie('side_cookie') === "show") {
          // code for showing side bar
      }
      else {
          // code for hiding the side bar
      }
      

      【讨论】:

      • Cyber​​nate 的例子不就是这样吗? ..他试图使用 $(this).text() 来设置 cookie 值,但它没有工作..如果它不是你能举个例子,因为这是第一次使用 cookie thx。
      【解决方案3】:

      好的 thx 伙计们,但我把它整理好了,它的代码比我想要的要多得多,因为它有很多 .show()/.hide() 而不是 .toggle() 但它现在可以工作了:

      $('a#hide').click(function(){
        $('a#hide,#sidebar').hide();
        $('a#show').show();
        $.cookie('side_cookie_hidden', 'hidden');
        $.cookie('side_cookie_show', null);
       return false;
      });
      
      $('a#show').click(function(){
        $('a#show').hide();
        $('a#hide,#sidebar').show();
        $.cookie('side_cookie_show', 'show');
        $.cookie('side_cookie_hidden', null);
       return false;
      });
      
      if($.cookie('side_cookie_hidden')) { 
      $('a#show').show();
      $('a#hide,#sidebar').hide(); 
         } else {
      $('a#show').hide();
      $('a#hide,#sidebar').show(); 
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-10-26
        • 1970-01-01
        • 2014-05-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-28
        相关资源
        最近更新 更多