gpt4 book ai didi

jquery - 页面刷新时,保留我为本地存储中的值设置的样式

转载 作者:行者123 更新时间:2023-12-01 04:52:10 25 4
gpt4 key购买 nike

样式应用并且本地存储工作正常,但是当我刷新页面时,样式不会再次应用于链接。这些值仍然在本地存储中,但它不会在页面上直观地显示。我如何进行检查以将这些样式应用于本地存储中的数组中的值。

$(function () {
var favorite = localStorage.getItem('favorite');
if (favorite !== null) {
favorite = JSON.parse(favorite) || [];
$(this).css('background-image', 'url(../assets/img/heart-red.svg)');
$(this).css('background-color', '#fefefe');
}
$(".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));
});
});

最佳答案

您始终可以在加载/就绪时应用样式

$(function(){
var favorite = localStorage.getItem( 'favorite' );
if (favorite !== null){
favorite = JSON.parse(favorite);
...
(apply styles to all pet-ids in the favorites array)
}
});

编辑 8/22好的,我想您需要编辑代码以应用任一样式,具体取决于该元素是否包含在最喜欢的数组中,即。

您可能需要更换线路

 if (favorite !== null) {
favorite = JSON.parse(favorite) || [];
$(this).css('background-image', 'url(../assets/img/heart-red.svg)');
$(this).css('background-color', '#fefefe');
}

if (favorite !== null) {
favorite = JSON.parse(favorite) || [];

$(".favorites").each(function(ix,el){
var petid = $(this).attr("pet-id");
if(favorite.indexOf(petId) === -1){
$(this).css('background-image', 'url(../assets/img/heart-full.svg)');
$(this).css('background-color', '#25aae3');
}else{
$(this).css('background-image', 'url(../assets/img/heart-red.svg)');
$(this).css('background-color', '#fefefe');
}
}

如果最喜欢的数组中有一种样式,此代码将应用一种样式;如果数组中缺少该样式,则此代码将应用另一种样式。

<小时/>

此外,为了解决评论中的问题,您可以在一行中应用多个 css 样式。

 $(domelement).css({ "background-color": "#fefefe", "background=image": "url(../assets/img/heart-red.svg" });

此表示法允许您将 css 数组移动到文件中的可重用属性中,即...

  var avaliable =  { "background-color": "#fefefe", "background=image": "..." };
var selected = { .... }

然后使用它们

  $(domelement).css(available);

关于jquery - 页面刷新时,保留我为本地存储中的值设置的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18348210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com