2013-09-28 61 views
3

我想給訪問者提供能夠標記他選擇的容器的能力,以便讓他能夠僅顯示他/她最喜歡的容器。我無法實現的是將他們的收藏夾存儲在cookie中,這樣他們每次訪問我的網站時都不必從頭開始標記它們(總共有36個容器)。我已經閱讀了jquery cookie插件文檔,也搜索了堆棧溢出,並且學習了幾個教程,並且還沒有關於如何使用它的任何線索。謝謝。jQuery cookie記住多個div的類

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"); 
}); 

回答

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); 
}); 
+0

皮特,我不知道該怎麼感謝你的男人!工作完美! – ArgGeo