localStorage, saving a class using toggleClass

后端 未结 3 1363
陌清茗
陌清茗 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:12

    Based on your reply to a previous answer (ID's are too cumbersome)

    Here is another approach. You can use their index as the localStorage value. HOWEVER, the number of the item elements must not change AND they don't change ordering.

    if (typeof(localStorage) == 'undefined') {
      document.getElementById("result").innerHTML =
        'Your browser does not support HTML5 localStorage. Try upgrading.';
    } else {
      // highlight the selected item
      if (localStorage.getItem("fav") != null) {
        getFav = localStorage.fav;
        $('.item').eq(getFav).addClass('favorites');
      }
    }
    
    $(document).ready(function() {
      $('.btn').on('click', function() {
        getFav = localStorage.fav;
    
        // clear all highlights
        $(".item").removeClass('favorites');
    
        // get the selected item then its index, then store in getFav
        var selectedItem = $(this).closest(".item");
        getFav = $('.item').index(selectedItem);
        selectedItem.toggleClass('favorites');
    
        // store the value in localStorage
        if (selectedItem.hasClass('favorites')) {
          localStorage.setItem('fav', getFav);
        } else {
          localStorage.removeItem('fav');
        }
    
      });
    });
    

    Here is a codepen: http://codepen.io/anon/pen/pJYroL

    NOTE I really recommend that you apply ID to the elements if you can. That will be more flexible. :)

提交回复
热议问题