使用jQuery cookie.js来记住隐藏/显示元素? [英] Using jQuery cookie.js to remember hide/show element?

查看:328
本文介绍了使用jQuery cookie.js来记住隐藏/显示元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了一个很好的教程,介绍如何在页面上显示和隐藏某个div。我得到的代码工作正常,但我想扩展是显示/隐藏在页面加载。我找到一个解决方案jQuery cookie是答案..如果我知道如何写的实际代码是..这里是当前片段:

I have found a great tutorial on how to show and hide a certain div on a page. I got the code working fine, but I would like to extend is to that the show/hide is remembered on page loads. I've looked for a solution jQuery cookie was the answer.. if I'd knew how to write the actual code that is.. Here's the current snippet:

<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>

任何想法如何添加cookies以记住用户的选择?代码示例将是伟大的,因为我仍然试图掌握jQuery / Javascript一般:)

Any idea how I can add the cookies to remember the selection from the user? A code sample would be great since I'm still trying to grasp jQuery/Javascript in general :)

提前感谢:)

推荐答案

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

Should be pretty easy. When you show the div add some code like:

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

...当您隐藏div时:

...and when you hide the div:

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

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

...and then at the top of your code where you've got:

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']();

:)

这篇关于使用jQuery cookie.js来记住隐藏/显示元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆