3

I would like to give the ability to a visitor to mark the containers of his choice in order to give him the ability to display only his/her favorite containers. What I cannot achieve is store their favorites in a cookie so they do not have to mark them from the beginning every time they visit my website (there are 36 containers in total). I have read the jquery cookie plugin documentation, also searched stack overflow and followed several tutorials and still have not any clue on how to use it. Thanks.

HTML

<div class="panel-player-favorite-option">
    <div class="not-favorite"></div>
</div>
<div class="panel-player-favorite-option">
    <div class="not-favorite"></div>
</div>
<div class="panel-player-favorite-option">
    <div class="not-favorite"></div>
  </div>
<div class="panel-player-favorite-option">
    <div class="not-favorite"></div>
</div>

JQUERY

jQuery('.panel-player-favorite-option').click(function() {
    jQuery(this).children().toggleClass("favorite not-favorite");
});
4

1 回答 1

3

首先,我假设您对每个选项元素都有唯一的标识符。我为每个元素添加了 ID。我还建议您使用该选项本身来拥有favorite该类,从而消除在所有选定选项的子项上切换该类的歧义。

这是我生成的 HTML:

<div id="option-1" class="panel-player-favorite-option"></div>
<div id="option-2" class="panel-player-favorite-option"></div>
<div id="option-3" class="panel-player-favorite-option"></div>
<div id="option-4" class="panel-player-favorite-option"></div>

然后这段代码对我有用,使用jquery.cookie.js

// set cookie name
var COOKIE_NAME = 'the_cookie';

// set cookie to automatically use JSON format
jQuery.cookie.json = true;

// retrieve or initialize favorites array
var favorites = jQuery.cookie(COOKIE_NAME) || [];

// collect all option elements in the dom
var options = jQuery('.panel-player-favorite-option');

// restore favorites in dom
for(var id in favorites)
{
    options.filter('#'+favorites[id]).addClass("favorite");
}

options.click(function() {
    // dom element
    var element = jQuery(this);

    // element id
    var id = element.attr('id');

    // toggle favorite class on the element itself
    element.toggleClass("favorite");

    // add or remove element id from array of favorites
    if(element.hasClass("favorite"))
        favorites.push(id);
    else
        favorites.splice(favorites.indexOf(id),1);

    // store updated favorites in the cookie
    jQuery.cookie(COOKIE_NAME, favorites);
});
于 2013-09-29T00:16:46.210 回答