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

如何点击删除按钮移除LocalStorage数组中的指定数据?

修正LocalStorage数组元素删除功能的方案

问题根源

原删除函数的错误在于:LocalStorage中存储的是整个数组的JSON字符串(键为title和description),而不是单个元素的独立键。直接用removeItem("title[${i}]")找不到对应的键,自然删不掉数据。

修正步骤

  • 调整删除逻辑:先取出完整数组,用splice删除对应索引的元素,再将修改后的数组重新存回LocalStorage
  • 修复变量声明:给全局作用域的变量加上let/const,避免全局变量污染
  • 初始化拼接容器:table1初始值设为空字符串,避免拼接后出现undefined前缀
  • 移除重复ID:循环生成的td不要用重复ID,换成class或者直接去掉

修正后的完整代码

let title, description;

function validate() {
  title = document.getElementById('title').value;
  description = document.getElementById('description').value;
  if (title === '') {
    alert("Please add title");
  } else if (description === '') {
    alert("Please add description");
  } else {
    document.getElementById("myform").reset();
    store(title, description);
  }
}

function store(title, description) {
  // 加载现有数组(不存在则默认空数组)
  let _title = JSON.parse(localStorage.getItem("title") || "[]");
  let _description = JSON.parse(localStorage.getItem("description") || "[]");
  _title.push(title);
  _description.push(description);
  localStorage.setItem("title", JSON.stringify(_title));
  localStorage.setItem("description", JSON.stringify(_description));
  window.location.reload();
}

// 声明变量并设置默认空数组,避免LocalStorage为空时报错
const get_title = JSON.parse(localStorage.getItem("title")) || [];
const get_description = JSON.parse(localStorage.getItem("description")) || [];
let table1 = '';

// 循环时用let声明i,避免全局变量污染
for (let i = 0; i < get_title.length; i++) {
  if (get_title[i] == null) {
    console.log("null");
  } else {
    table1 += `
    <tr>
      <th scope="row">${i + 1}</th>
      <td class="tit">${get_title[i]}</td>
      <td class="descripti">${get_description[i]}</td>
      <td> 
        <button type="button" 
             class="btn btn-sm btn-danger"
             onclick="del(${i})">
          Delete
        </button>
      </td>
    </tr>`;
  }
}

document.getElementById('table1').innerHTML = table1;

function del(index) {
  // 取出当前存储的数组,为空则用默认空数组
  let titles = JSON.parse(localStorage.getItem("title")) || [];
  let descriptions = JSON.parse(localStorage.getItem("description")) || [];
  
  // 删除对应索引的元素
  titles.splice(index, 1);
  descriptions.splice(index, 1);
  
  // 将修改后的数组重新存回LocalStorage
  localStorage.setItem("title", JSON.stringify(titles));
  localStorage.setItem("description", JSON.stringify(descriptions));
  
  window.location.reload();
}

额外优化说明

  • 用===代替==做严格相等判断,避免类型转换带来的意外
  • 给get_title和get_description设置默认空数组,防止LocalStorage为空时出现length读取报错
  • 移除了原代码中按钮区域的无效**标记

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 15:00:49