我正在使用本地存储将值保存到数组中并根据数组中的值更改锚的样式,当我单击其中一个锚并刷新时应用样式,但是当我选择两个锚和刷新样式消失。
$(function(){
var favorite = localStorage.getItem( 'favorite' );
if (favorite !== null){
favorite = JSON.parse(favorite) || [];
}
$('.favorites' ).each(function() {
if($(this).attr('data-petid') == favorite){
$(this).css('background-image', 'url(../assets/img/heart-red.svg)');
$(this).css('background-color', '#fefefe');
}
});
// This function changes the color of the heart on the landing page and stores the values into local storage
$(".favorites").click(function() {
var favorite = localStorage.getItem( 'favorite' );
var petid = $(this).attr('data-petid');
var index;
favorite = JSON.parse(favorite) || [];
if ((index = favorite.indexOf(petid)) === -1) {
favorite.push(petid);
$(this).css('background-image', 'url(../assets/img/heart-red.svg)');
$(this).css('background-color', '#fefefe');
}else {
$(this).css('background-image', 'url(../assets/img/heart-full.svg)');
$(this).css('background-color', '#25aae3');
favorite.splice(index, 1);
}
localStorage.setItem('favorite', JSON.stringify(favorite) );
});
});