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

JavaScript待办列表报错:Uncaught ReferenceError: itemsjson未定义

解决Uncaught ReferenceError: itemsjson is not defined错误

错误原因及修复点:

  1. 未定义变量引发引用错误:
    localStorage.getItem(itemsjson)里的itemsjson是未声明的变量,localStorage的键名必须是字符串,应改为localStorage.getItem('itemjson')。

  2. 变量命名拼写错误:
    你创建的数组是itemjsonArray,但在JSON.stringify(itemsjsonArray)里误写成了itemsjsonArray(多了一个s),导致无法正确序列化数组。

  3. 全局变量污染问题:
    代码中的tatti、tit、desc、itemjsonArray都未用let/const声明,会自动成为全局变量,建议添加声明避免污染。

  4. 未处理已有数据的场景:
    当前代码只处理了localStorage为空的情况,若已有数据,需要先解析出数组再添加新项。

修正后的完整代码:

<!doctype html>
<html lang="en">
<div class="form">
    <label for="formGroupExampleInput" class="form-label">Example label</label>
    <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input placeholder">
  
      <label for="formGroupExampleInput2" class="form-label">Another label</label>
    <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input placeholder"> <br>

    <button type="submit" id="add" class="btn btn-primary">Sign in</button>

  </div>

  <table class="table">
    <thead>
      <tr>
        <th scope="col">Item</th>
        <th scope="col">Item Description</th>
        <th scope="col">Actions</th>
      </tr>
    </thead>
    <tbody>
      <tr>
  
        <td>Parvinder</td>
        <td>Hello, Parvinder how are you?</td>
        <td><button type="button" class="btn btn-primary btn-sm">Small button</button></td>
      </tr>
    </tbody>
  </table>
<script>
    const addBtn = document.getElementById("add");
    addBtn.addEventListener("click", () => {
      console.log("updating");

      const title = document.getElementById('formGroupExampleInput').value;
      const description = document.getElementById('formGroupExampleInput2').value;
      
      // 从localStorage获取数据,为空则初始化空数组
      let itemArray = JSON.parse(localStorage.getItem('itemjson')) || [];
      // 添加新项
      itemArray.push([title, description]);
      // 存回localStorage
      localStorage.setItem('itemjson', JSON.stringify(itemArray));
      
      // 可在此添加页面列表更新逻辑,比如把新项渲染到表格中
    })
</script>

  </center>
</html>

额外说明:

修正后的代码优化了变量名(更语义化),同时统一处理了localStorage有无数据的情况,每次点击都会先获取现有数组,添加新项后再存回,避免覆盖已有数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 17:34:57