首页 > 解决方案 > 页面刷新后如何检查图标

问题描述

所以我制作了一个带有图标的 div,当用户单击该图标时,电影的 id 被推送到本地存储中。因此,当用户刷新页面时,我希望该图标保持一颗完整的心,而不是一颗空心。我怎么能这样做?

var favorites = JSON.parse(localStorage.getItem('favorites')) || [];
// add class 'fav' to each favorite
const whiteHeart = 'fa fa-heart-o fa-2x';
const blackHeart = 'fa fa-heart fa-2x';
const button = document.querySelector('#heart_icon');

$('#heart').click(function() {
  const movie_id = $(this).attr('data-id');
  index = favorites.indexOf(movie_id);
  if (!movie_id) return;
  // item is not favorite
  if (index == -1) {
    favorites.push(movie_id);
    button.className = blackHeart;
    // item is already favorite
  } else {
    favorites.splice(index, 1);
    button.className = whiteHeart;
  }
  // store array in local storage
  JSON.parse(localStorage.setItem('favorites', JSON.stringify(favorites)));
})
<div id="heart" data-id="ID1"> <i id="heart_icon" class="fa fa-heart-o fa-2x"></i> </div>

标签: javascripthtml

解决方案


请注意,如果你有多个心脏,你需要使用一个类

$('.heart').click(function() {

在您当前的代码中,您需要

  1. 改为
    JSON.parse(localStorage.setItem('favorites', JSON.stringify(favorites))刚刚 localStorage.setItem('favorites', JSON.stringify(favorites))

  2. onload 运行存储的收藏夹

建议代码https://plungjan.name/SO/heartslocalstorage.html

let favorites;
const toggleIcon = ($icon, id) => {
  const isFav = favorites.indexOf(id) !== -1; // or includes for non-IE11 (polyfill on my site)
  $icon
    .toggleClass("fa-heart-o", !isFav)
    .toggleClass("fa-heart", isFav); // swap classes
};
$(function() {
  favorites = JSON.parse(localStorage.getItem('favorites')) || [];

  $('.heart').on("click", function() {
    const id = $(this).attr('data-id');
    const $icon = $(this).find("i");
    if (favorites.indexOf(id) === -1) favorites.push(id); // save the movie
    else {
      const index = favorites.indexOf(id); // get the movie position
      favorites.splice(index, 1); // and delete it from favourites
    }
    toggleIcon($icon, id);
    // store array in local storage
    localStorage.setItem('favorites', JSON.stringify(favorites));
  })

  $('.heart[data-id]').each(function() { // set the classes on ALL hearts
    const id = $(this).data("id");
    const $icon = $(this).find("i");
    toggleIcon($icon, id);
  });
});
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

<div class="heart" data-id="ID1"> <i id="heart_icon" class="fa fa-heart-o fa-2x"></i> </div>
<div class="heart" data-id="ID2"> <i id="heart_icon" class="fa fa-heart-o fa-2x"></i> </div>
<div class="heart" data-id="ID3"> <i id="heart_icon" class="fa fa-heart-o fa-2x"></i> </div>

推荐阅读