javascript - 使用 cookie 持久化 div 切换状态

标签 javascript jquery plugins cookies

使用下面的代码示例,我如何利用 jquery cookie 插件,以便每个 div 元素的切换状态在浏览器 session 之后持续存在。

谢谢。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

        <script type="text/javascript">

        jQuery.fn.slideFadeToggle = function(speed, easing, callback) {
        return this.animate({opacity: 'toggle', height: 'toggle'}, speed, easing, callback);  
        };

        $(document).ready(function(){
         $('.toggle').show();
         $('.hide').click(function(){
          var t = $(this);
          // toggle hidden div
          t.parent().find('.toggle').slideFadeToggle(400, function(){
           // determine which image to use if hidden div is hidden after the toggling is done
           var imgsrc = ($(this).is(':hidden')) ? 'http://i47.tinypic.com/vg0hu0.gif' : 'http://i45.tinypic.com/281tsle.gif';
           // update image src
           t.attr('src', imgsrc );
          });
         })
        })
        </script> 

        </head>
        <body>

        <div class="wrapper">
         <img class="hide" src="http://i45.tinypic.com/281tsle.gif" /> Header Text 1
         <div class="toggle">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
        </div>

        <p>
        <div class="wrapper">
         <img class="hide" src="http://i45.tinypic.com/281tsle.gif" /> Header Text 2
         <div class="toggle">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
        </div>
        </p>
      </body>
    </html>

最佳答案

只要考虑您需要什么,您需要做的第一件事就是为每个“包装器”部分指定一个 ID。此 ID 标识跨页面 View 的每个可切换部分。它不需要与 id 属性相同,但如果包装器 ID 与相应 id 属性值相同,则可能最简单>div.wrapper 元素。

然后,假设您希望所有部分最初都可见,您的 cookie 可以存储隐藏部分的 ID 列表。这样,没有 cookie 就意味着没有隐藏部分,因此所有部分最初都是可见的。

每次用户隐藏一个部分时,您都会更新 cookie 值以包含新隐藏部分的 ID。每次用户取消隐藏某个部分时,您都会更新 cookie 值以排除现在可见部分的 ID。

最后,在页面加载时,您遍历 cookie 中的 ID,隐藏列出的部分。

这是帮助您入门的代码:

<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery.cookie.js"></script>
<script type="text/javascript">

jQuery.fn.slideFadeToggle = function(speed, easing, callback) {
    return this.animate({opacity: 'toggle', height: 'toggle'}, speed, easing, callback);  
};

/**
 * \returns an array of section IDs
 */
function getHiddenSectionIDs()
{
    var arr = ($.cookie('hidden_section_ids') || '').split(',');
    for (var i = 0; i < arr.length; ++i) {
        arr[i] = $.trim(arr[i]);
        if (arr[i].length <= 0)
            arr[i] = null;
    }
    return arr;
}

function setHiddenSectionIDsCookie(hiddenSectionIDs)
{
    var str = '';
    for (var i = 0; i < hiddenSectionIDs.length; ++i) {
        var id = hiddenSectionIDs[i];
        if (id !== null)
            str += ',' + id;
    }

    $.cookie('hidden_section_ids', str);
}

function toggle(t, updateCookie) {
    var t = $(t);
    var parent = t.parent();

    // toggle hidden div
    parent.find('.toggle').slideFadeToggle(400, function(){
        // determine which image to use if hidden div is hidden after the toggling is done
        var imgsrc = ($(this).is(':hidden')) ? 'http://i47.tinypic.com/vg0hu0.gif' : 'http://i45.tinypic.com/281tsle.gif';
        // update image src
        t.attr('src', imgsrc );

        if (updateCookie || updateCookie === undefined) {
            var hiddenSectionIDs = getHiddenSectionIDs();
            if (parent.find('.toggle').is(':hidden'))
                hiddenSectionIDs.push(parent.attr('id'));
            else {
                for (var i = 0; i < hiddenSectionIDs.length; ++i) {
                    var id = hiddenSectionIDs[i];
                    if (id == parent.attr('id'))
                        hiddenSectionIDs[i] = null;
                }
            }

            setHiddenSectionIDsCookie(hiddenSectionIDs);
        }
    });
}

$(document).ready(function(){
    var hiddenSectionIDs = getHiddenSectionIDs();
    for (var i = 0; i < hiddenSectionIDs.length; ++i) {
        var id = hiddenSectionIDs[i];
        if (id !== null) {
            var section = $('#' + hiddenSectionIDs[i]);
            if (section) {
                toggle(section.find('.hide'), false);
            }
        }
    }

    $('.hide').click(function(){
        toggle(this);
    });
});
</script> 

</head>
<body>

<div id="section-1" class="wrapper">
<img class="hide" src="http://i45.tinypic.com/281tsle.gif" /> Header Text 1
<div class="toggle">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
</div>

<p>
<div id="section-2" class="wrapper">
<img class="hide" src="http://i45.tinypic.com/281tsle.gif" /> Header Text 2
<div class="toggle">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
</div>
</p>
</body>
</html>

它远非经典/完善的解决方案,但我已经对其进行了测试,并且有效。

我用了this jQuery cookie plug-in .

关于javascript - 使用 cookie 持久化 div 切换状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3136511/

相关文章:

javascript - 引用错误 : WebSocket is not defined

javascript - Angular Directive(指令)中的回调函数

javascript - 当没有设置 value 属性时,val() 返回 html() 而不是 <option> 标签的 undefined

javascript - 如何居中和调整jqwidget模拟时钟的大小?

javascript - <select> 中 <option> 的互斥?

testing - 在 Jenkins 中显示单个测试结果的历史记录 - 附加插件或配置问题?

javascript - 如何根据多个条件过滤嵌套的对象数组?

javascript - 如何在单击按钮时获取 slider 值?

maven::install multiple third-party artifacts to local repository 一次从文件系统

javascript - 如何使用 asp.net 禁用 Firefox 默认 PDF 查看器/插件?