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

如何用纯JS实现向Div追加内容并将日期与分数存入localStorage?

高分榜功能实现问题及修复方案

问题描述

我正在尝试实现一个高分榜功能,希望玩家达成胜利条件时,将最终分数和日期追加到指定div中,并存入localStorage。编写的代码如下:

function saveHighScore() {
  let date = new Date()
  let highScoreDivNew = document.createElement("div")
  let highScoreNumbers = document.innerHTML = `Your high score is ${pikmin.numberOf} on ${date}!`
  highScoreDiv.appendChild(highScoreDivNew)
  document.body.insertBefore(highScoreNumbers, highScoreDivNew)
  localStorage.setItem("highScoreContent", highScoreNumbers)
}

运行时出现错误:

script.js:63 Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
    at saveHighScore (script.js:63:18)
    at updateDayTimer (script.js:138:9)
    at HTMLButtonElement.<anonymous> (script.js:103:5)

我知道这是因为appendChild的参数不是DOM元素,但我以为创建的highScoreDivNew符合要求。我有一段能正常工作的localStorage示例代码:

dayTimer.innerHTML = `<p>You have taken ${dayCounter}/6 days!</p>`
dayTimer.class = "save-timer"

function saveDayTimer() {
    localStorage.setItem("dayCounter", dayTimer)
}

我主要想用document.createElement创建元素,但对innerHTML的用法有疑问,目标是玩家胜利时向highScoreDiv动态插入高分元素,不需要使用JSON或jQuery。

错误原因分析

  • document.innerHTML误用:你直接修改了整个文档的innerHTML,还把highScoreNumbers赋值成了字符串而非DOM元素,导致后续insertBefore传入字符串参数触发错误。
  • DOM操作顺序混乱:你先把空的highScoreDivNew追加到highScoreDiv,之后才尝试添加内容,且insertBefore的参数逻辑完全错误。
  • localStorage存储方式错误:你的示例代码里存储DOM元素,实际是存了它的默认字符串值,这不是正确做法,应该存储文本内容。

修复后的代码

function saveHighScore() {
  // 格式化日期,避免默认Date输出过于冗长
  const date = new Date().toLocaleString();
  // 创建新的高分条目元素
  const highScoreDivNew = document.createElement("div");
  // 给新元素设置高分内容
  highScoreDivNew.innerHTML = `Your high score is ${pikmin.numberOf} on ${date}!`;
  
  // 把新元素追加到目标高分容器中
  highScoreDiv.appendChild(highScoreDivNew);
  
  // 读取本地存储已有的高分记录,无记录则为空
  let existingScores = localStorage.getItem("highScoreContent");
  existingScores = existingScores ? existingScores + "<br>" : "";
  // 拼接新记录后存入本地存储
  const newScoreContent = existingScores + highScoreDivNew.innerHTML;
  localStorage.setItem("highScoreContent", newScoreContent);
}

额外补充

如果需要页面加载时自动恢复之前的高分记录,可以在页面初始化时添加这段代码:

window.addEventListener('load', function() {
  const savedScores = localStorage.getItem("highScoreContent");
  if (savedScores) {
    highScoreDiv.innerHTML = savedScores;
  }
});

另外你之前的saveDayTimer代码存在隐患,正确的存储方式应该是存储元素的文本内容:

function saveDayTimer() {
  localStorage.setItem("dayCounter", dayTimer.innerHTML);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 21:37:33