localStorage,使用toggleClass保存类

问题描述:

在涉及到localStorage时,我似乎无能为力。我想通过切换一个类来设置一个喜欢div组中任何div的方式。我可以让toggleClass处理单个div并保存,但localStorage将所有div保存为收藏夹,而不仅仅是设置了toggleClass的div。显然我错过了一些东西。

I am clueless when it comes to localStorage it seems. I want to set up a way favorite any div in a group of div's by toggling a class. I can get the toggleClass to work on the individual div and be saved but localStorage saves all the div's as favorites, not just the one with the toggleClass set. Obviously I am missing something.

jsfiddle simple example

localStorage代码:

localStorage code:

if (typeof (localStorage) == 'undefined') {
document.getElementById("result").innerHTML = 'Your browser does not support HTML5 localStorage. Try upgrading.';
} else {
if (localStorage.getItem("fav") != null) {
    getFav = localStorage.fav;
    $(".item").addClass('favorites');
}
}
$(document).ready(function () {
$('.btn').on('click', function () {
    getFav = localStorage.fav;
    //$(".item").removeClass('favorites');
    //localStorage.removeItem('background');
    $(this).closest(".item").toggleClass('favorites');
    if ($(this).closest(".item").hasClass('favorites')) {
    localStorage.setItem('fav', 'favorites');

}else{
    localStorage.removeItem('fav');
}

});
});

问题在于

$(".item").addClass('favorites');

它将类添加到所有.items,显然它不应该。

It adds the class to all .items and obviously it should not.

任何帮助都将不胜感激!

Any help would be appreciated!

如果其他答案问题不够,这里是一个允许你有多个div在重新加载后维持状态而不只是一个的解决方案。

In case the other answers questions do not suffice here is a solution that allows you to have multiple divs that will maintain state after reload rather than just one.

http://codepen.io/anon/pen/WvmEbX

if (typeof(localStorage) == 'undefined') {
  document.getElementById("result").innerHTML =
    'Your browser does not support HTML5 localStorage. Try upgrading.';
} else {
    $(".item").each(function(i, el) {
      if (localStorage['fav' + i] == 'favorites') {
        $(this).addClass('favorites');
      }
    });
}
$(document).ready(function() {
  $('.btn').on('click', function() {
    var $item = $(this).closest('.item');
    var index = $('.item').index($item);
    $item.toggleClass('favorites');
    if ($item.hasClass('favorites')) {
      localStorage.setItem('fav' + index, 'favorites');
    } else {
      localStorage.removeItem('fav' + index);
    }
  });
});