javascript - 页面刷新后如何检查图标
问题描述
所以我制作了一个带有图标的 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>
解决方案
请注意,如果你有多个心脏,你需要使用一个类
$('.heart').click(function() {
在您当前的代码中,您需要
改为
JSON.parse(localStorage.setItem('favorites', JSON.stringify(favorites))
刚刚localStorage.setItem('favorites', JSON.stringify(favorites))
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>
推荐阅读
- java - 线程“主”java.security.InvalidKeyException 中的异常:非法密钥大小。键的字符长度为 44
- apache-spark - 如何计算相同元素的列中的值
- python - 无法在 Ubuntu 20.04 上安装 1.x 版本的 Tensorflow
- laravel - 为什么 Laravel 使用默认队列连接,即使我指定了具有不同连接的队列
- swift - Xcode 模拟器显示为很小
- python - 允许密码为任意长度 Crypto
- c - 链表插入丢失
- javascript - 有没有办法知道下载保存在javascript中的位置
- python - 我是编码新手,只是不明白这个错误代码的含义
- php - Laravel - 控制器和模型之间的区别