You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

遍历存储布尔值添加对应类 实现页面刷新后交互状态持久化

问题描述

我在多个页面中放置了一批带有独立ID的交互项,目前已实现点击时创建Cookie、根据元素是否存在指定类将Cookie值更新为true或false的逻辑,但已添加的类状态无法在页面刷新后保留。检索了大量相关资料仍未找到适配的实现示例,需要实现页面加载时检测对应Cookie是否存在,若存在则为对应元素(共十余个)添加指定类。

初始实现代码

<script>
  setCookie = (cName, cValue, expDays) => {
    var date = new Date();
    date.setTime(date.getTime() + (expDays * 24 * 60 * 60 * 1000));
    var expires = "expires="+ date.toUTCString();
    document.cookie = cName + "=" + cValue + ";" + expires + "; path=/";
  }

   getCookie = (cName) => {
    const name = cName + "=";
    const cDecoded = decodeURIComponent(document.cookie);
    const cArr = cDecoded.split("; ");
    var value;
    cArr.forEach((val) => {
       if (val.indexOf(name) === 0) value = val.substring(name.length);
     });
    return value;
  };

  $('.accomo-fav').on('click', function() {
    var likeVal = $(this).attr('id')
    if ($(this).hasClass('active-fav')) {
      setCookie(likeVal, false, 90)
      $(this).removeClass('active-fav') 
    } else {
      $(this).addClass('active-fav')
      setCookie(likeVal, true, 90)
    }
  })
</script> 

页面元素结构

使用的容器元素精简代码如下:

<div class="room-row-container">
    <div class="lg:w-1/2 w-full relative search-image">
        <img src="<?php the_post_thumbnail_url(); ?>" alt="Thumbnail Image" class="absolute object-cover w-full h-full">
    </div>
    <div class="lg:w-1/2 w-full relative lg:p-8">
        <div class="w-full flex flex-row items-center justify-between mb-8">
            <h4 class="text-3xl mb-2"><?php the_title(); ?></h4>
            <svg class="accomo-fav" id="<?php the_ID(); ?>" width="22" height="21" viewBox="0 0 22 21" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M15.5 1C13.76 1 12.09 1.81 11 3.09C9.91 1.81 8.24 1 6.5 1C3.42 1 1 3.42 1 6.5C1 10.28 4.4 13.36 9.55 18.04L11 19.35L12.45 18.03C17.6 13.36 21 10.28 21 6.5C21 3.42 18.58 1 15.5 1Z" stroke="black" stroke-width="2" stroke-linejoin="round"/>
                <path d="M15.5 1C13.76 1 12.09 1.81 11 3.09C9.91 1.81 8.24 1 6.5 1C3.42 1 1 3.42 1 6.5C1 10.28 4.4 13.36 9.55 18.04L11 19.35L12.45 18.03C17.6 13.36 21 10.28 21 6.5C21 3.42 18.58 1 15.5 1Z" stroke="black" stroke-width="2" stroke-linejoin="round"/>
            </svg>
        </div>              
    </div>
</div>

最初思路是遍历所有room-row-container块,检测对应ID的Cookie是否已创建,但始终未理清实现逻辑。

解决方案

重构脚本后改用localStorage实现需求,编写了简洁的点击交互逻辑实现收藏项的存储与移除,页面加载时遍历localStorage所有键,为匹配的元素添加active-fav类,最终实现代码如下:

$('.accomo-fav').on('click', function() {
    var item = $(this).attr('id');
    if ($(this).hasClass('active-fav')) {
      $(this).removeClass('active-fav')
      localStorage.removeItem(item)
    } else {
      localStorage.setItem(item, true)
      $(this).addClass('active-fav')
    }
  })
  
  var arrayOfKeys = Object.keys(localStorage);
  console.log(arrayOfKeys)

  arrayOfKeys.map( function(key) {
    console.log(key)
    $('.accomo-fav[data-like="' + key + '"]').addClass('active-fav')
  })

内容的提问来源于stack exchange,提问作者Sam St Aubyn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 05:27:21