gpt4 book ai didi

php - localStorage 不维护 jquery 单击函数对页面刷新的影响

转载 作者:行者123 更新时间:2023-11-28 14:09:45 25 4
gpt4 key购买 nike

我正在从 php 数组中提取员工姓名列表,并将其显示在 html 页面上。单击员工姓名时(通过 jQuery),他们的名字变为红色(通过 css)。现在我有一个使用 localStorage 的函数,因为我试图保持被点击的员工在页面刷新时的红色状态,或者无论哪个用户查看该页面,但从现在开始,当我刷新页面时,红色字体恢复正常如果没有被点击。

我曾尝试在 jQuery 函数中使用 localStorage 来维护基于从 PHP 数组中提取并以 HTML 显示的员工 ID# 的状态。

HTML/PHP

 <td>
<span class="EmpFullName" id="<?php echo trim($data['Id']);?>"><strong>
<?php echo $data['EmpFullName'];?></strong><br></span>
</td>

jQuery


$( document ).ready(function() {
let ls = window.localStorage;
let storeKey = 'item-clicked';

$('.EmpFullName').click(function() {
$(this).toggleClass('clicked');

if(ls)
{
let str = ls.getItem(storeKey), arr;
if(str)
{
try{
arr = JSON.parse(str);
}
catch(e){
};
}
if(!Array.isArray(arr))
{
arr=[];
}

let clicked = $(this).hasClass('clicked');
let index = arr.indexOf(this.id);
if(clicked)
{
if(index === -1)
{
arr.push(this.id);
}
}
else
{
if(index > -1)
{
arr.splice(index, -1);
}
}
ls.setItem(storeKey, JSON.stringify(arr));
}
});

let str = ls ? ls.getItem(storeKey) : '';
if(str)
{
let arr;
try{
arr = JSON.parse(str);
}
catch(e){
}

if(Array.isArray(arr))
{
arr.forEach(function(id)
{
$('#' + id).toggleClass('clicked');
});
}
}
});

CSS

 .clicked{
color: red;
font-weight: bold;
}

最佳答案

问题在于您尝试获取 ID 属性的方式。
this.id 未定义,您应该使用 $(this).attr('id')

此外,当从数组中删除元素时,您应该使用 arr.splice(index, 1); 而不是 arr.splice(index, -1);,因为第二个参数表示“要删除多少元素”。

关于一般代码风格,我建议您使用 return early pattern .

关于php - localStorage 不维护 jquery 单击函数对页面刷新的影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56706422/

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