首页 > 解决方案 > 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;
    }

标签: phpjqueryhtmlcss

解决方案


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

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

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


推荐阅读