【问题标题】:Using jQuery cookie.js to remember hide/show element?使用 jQuery cookie.js 来记住隐藏/显示元素?
【发布时间】:2011-04-11 21:25:13
【问题描述】:

我找到了一个关于如何在页面上显示和隐藏某个 div 的很棒的教程。我的代码工作正常,但我想扩展的是在页面加载时会记住显示/隐藏。我一直在寻找解决方案 jQuery cookie 就是答案。如果我知道如何编写实际的代码,那就是 .. 这是当前的 sn-p:

<script type="text/javascript">
jQuery(document).ready(function() {
 // hides the group_desciption as soon as the DOM is ready
 // (a little sooner than page load)
  jQuery('#group_desciption').hide();
 // shows the group_desciption on clicking the noted link
  jQuery('a#slick-show').click(function() {
 jQuery('#group_desciption').show('slow');
 return false;
  });
 // hides the group_desciption on clicking the noted link
  jQuery('a#slick-hide').click(function() {
 jQuery('#group_desciption').hide('fast');
 return false;
  });
 // toggles the group_desciption on clicking the noted link
  jQuery('a#slick-toggle').click(function() {
 jQuery('#group_desciption').toggle(400);
 return false;
  });
});</script>

知道如何添加 cookie 以记住用户的选择吗?一个代码示例会很棒,因为我仍在尝试总体上掌握 jQuery/Javascript :)

提前致谢:)

【问题讨论】:

    标签: jquery cookies hide show


    【解决方案1】:

    应该很容易。当您显示 div 时,添加一些代码,例如:

    jQuery.cookie('show_desc', 'yep');
    

    ...当你隐藏 div 时:

    jQuery.cookie('show_desc', 'nope');
    

    ...然后在您的代码顶部:

    jQuery('#group_desciption').hide();
    

    ...改成:

    var shouldShow = jQuery.cookie('show_desc') == 'yep';
    if( shouldShow ) { jQuery('#group_desciption').show(); }
    else {             jQuery('#group_desciption').hide(); }
    

    或者,或者:

    jQuery('#group_desciption')[jQuery.cookie('show_desc') == 'yep' ? 'show' : 'hide']();
    

    :)

    【讨论】:

    • 谢谢!!在一些帮助和混乱下,我得到了完美的工作!
    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多