localStorage, saving a class using toggleClass

后端 未结 3 1320
陌清茗
陌清茗 2021-01-17 06:51

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

3条回答
  •  温柔的废话
    2021-01-17 07:20

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

提交回复
热议问题