带有收藏夹选项的多图像页面-如何使用localStorage来记住哪些图像受到了青睐

Multiple image page with favourite option - how to use localStorage to remember which images have been favourited

本文关键字:图像 localStorage 受到了 何使用 选项 收藏夹      更新时间:2023-09-26

所以我有一个页面,上面有一个带有星形图标的图像,这样用户就可以喜欢了。每个图像都有这个。我希望用户能够点击,它会通过更改图像类来喜欢这些。使用localStorage意味着他们可以在未来的会话中返回,其中受支持的会话仍然受支持。到目前为止,我有:

if (window.localStorage) {
 var didTheyFave = $('.icon-star-empty').each(function() {
(this).click(function() {
    if($(this).hasClass('icon-star')) {
     $( this ).addClass( 'icon-star-empty' ); 
     $( this ).removeClass( 'icon-star' );
     var fav = false;
} else {
     $( this ).addClass( 'icon-star' ); 
     $( this ).removeClass( 'icon-star-empty' );
     var fav = true;
}
 localStorage.setItem('didTheyFave', fav);
 })
});
}

然后获取项目:

$(window).load(function() {
var favResult = localStorage.getItem('didTheyFave');
if ( favResult = true ) {
    $('.icon-star-empty').addClass( 'icon-star' ); 
}
}); // I know this last bit is incorrect but testing things to see if they work!
$(window).load(function() {
function assignFavStar(){
   $('.commonClassUsedforEachStar').each(function(index){
         //get localStorage item for each
          if ( favResult === true ) {//do this first
               $('.commonClassUsedforEachStar').addClass( 'icon-star' ); 
          } else {
                 $('.commonClassUsedforEachStar').addClass( 'icon-star-empty' ); 
           }
   });
}
}

如果你能做这样的事情,试试看,不是防弹的,但可以让你开始这样做。

if (window.localStorage) {
  var didTheyFave = $('.icon-star-empty').click(function() {
   if($(this).hasClass('icon-star')) {
     $( this ).addClass( 'icon-star-empty' ); 
     $( this ).removeClass( 'icon-star' );
     var fav = false;
 } else {
     $( this ).addClass( 'icon-star' ); 
     $( this ).removeClass( 'icon-star-empty' );
     var fav = true;
 }
 localStorage.setItem('didTheyFave', fav);
});
}

localStorage.setItem('didTheyFave', fav);这一行总是设置为true/false,并覆盖上一个值。您需要检查哪个设置为true,哪个设置为false。

您可以尝试在设置索引时使用索引,例如,当用户单击某个星形时,获取该星形的位置,获取该位置并将其添加到didTheyFave,因此现在您保存在localStorage中的密钥看起来像didTheyFave1didTheyFave2等等,您可以在检索时循环这些索引并设置true/false值。