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

如何为LocalStorage结合clone追加的元素添加关闭按钮与计数功能

解决方案

以下是直接可用的修改后代码,两个需求均已实现,同时修复了原代码中事件重复绑定、动态元素事件失效、存储逻辑错误的问题:


完整JavaScript代码

// 计数更新函数,每次元素增删时自动调用
function updateCount() {
  const total = $('.item-append .item-save').length;
  $('.count').text(total);
}

// 给克隆元素添加关闭按钮
function insertCloseBtn($el) {
  $el.append('<span class="close">×</span>');
}

// 页面初始化加载已存储的选中项
$('.item-all .item-save').each(function() {
  const storageKey = 'test' + this.dataset.id;
  if (localStorage.getItem(storageKey) === "true") {
    $(this).addClass('productad');
    const $clone = $(this).clone();
    insertCloseBtn($clone);
    $clone.appendTo('.item-append');
  }
});
// 初始化计数
updateCount();

// 左侧原始按钮点击逻辑(合并原重复绑定的事件)
$('.item-all .item-save').click(function() {
  const id = this.dataset.id;
  const $existClone = $(`.item-append [data-id=${id}]`);
  const newStatus = !$(this).hasClass('productad');

  // 同步状态和存储
  $(this).toggleClass('productad', newStatus);
  localStorage.setItem(`test${id}`, newStatus);

  // 同步克隆元素
  if (newStatus) {
    const $newClone = $(this).clone();
    insertCloseBtn($newClone);
    $newClone.appendTo('.item-append');
  } else {
    $existClone.remove();
  }
  // 更新计数
  updateCount();
});

// 关闭按钮点击逻辑(事件委托适配动态生成的元素)
$('.item-append').on('click', '.close', function(e) {
  e.stopPropagation();
  const $curItem = $(this).closest('.item-save');
  const id = $curItem.data('id');

  // 移除存储
  localStorage.removeItem(`test${id}`);
  // 移除当前克隆元素
  $curItem.remove();
  // 同步原始按钮状态
  $(`.item-all [data-id=${id}]`).removeClass('productad');
  // 更新计数
  updateCount();
});

新增CSS样式(关闭按钮+布局适配)

/* 追加区域按钮适配关闭按钮定位 */
.item-append .item-save {
  position: relative;
  margin: 10px 5px;
}
/* 关闭按钮样式 */
.item-append .close {
  position: absolute;
  top: -6px;
  right: -6px;
  width: 16px;
  height: 16px;
  line-height: 14px;
  text-align: center;
  font-size: 12px;
  background: #fff;
  color: #000;
  border-radius: 50%;
  border: 1px solid #ccc;
  cursor: pointer;
  font-weight: bold;
}

HTML代码无需修改,沿用原有结构即可

功能验证:

  • 点击左侧保存按钮自动同步右侧元素增删、计数更新、本地存储
  • 点击右侧元素的关闭按钮自动同步删除存储、更新左侧按钮状态、刷新计数
  • 页面刷新后已选中内容和计数自动恢复

内容的提问来源于stack exchange,提问作者Dasy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 05:24:04