我希望给予访客标记他所选择的容器的能力,以便让他能够只展示他/她最喜欢的容器。我不能做到的是把他们最喜欢的东西存储在一个曲奇里,这样他们就不必每次访问我的网站时就标记它们(总共有36个容器)。我已经阅读了jquery插件文档,还搜索了堆栈溢出,并遵循了几个教程,但仍然不知道如何使用它。谢谢。
<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");
});发布于 2013-09-29 00:16:46
首先,我假设每个选项元素都有唯一的标识符。我在每个元素中都添加了ids。我还建议您使用选项本身来拥有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);
});https://stackoverflow.com/questions/19072144
复制相似问题