使用cookie保持div切换状态

时间:2010-06-28 22:08:43

标签: javascript jquery plugins cookies

使用下面的代码示例,我如何利用jquery cookie插件,以便每个div元素的切换状态持续超出浏览器会话。

感谢。

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

1 个答案:

答案 0 :(得分:0)

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

然后,假设您希望最初看到所有部分,您的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