php - localStorage 不维护 jquery click 功能对页面刷新的影响
问题描述
我正在从 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 模式。
推荐阅读
- elasticsearch - Elasticsearch 读取模型与写入模型同步
- javascript - 如何使用 reactjs 为我的电子商务项目乘法?
- c# - 如何使用 MVVM 架构在 WPF 中设置组合框值
- firebase - 在 Firestore 中创建文档时如何使用自定义文档 ID
- android - binding.getRoot() - 无法解析方法
- php - PHP基于一个文本值过滤器查询所有列
- php - Illuminate \ Http \ Exceptions \ PostTooLargeException没有消息laravel 5.8
- react-native - React Native 动态堆栈屏幕数量
- java - 适配器中的 getActivity()
- android-studio - SO_REUSEPORT 在编译系统上不可用以在 Ubuntu 上运行 android 模拟器