我正在尝试弄清楚如何让localStorage在这里工作。我试图制作一个高分列表,它将用户在我所拥有的获胜条件下的最终得分,并将其附加到至少一个p或div中,然后保存它。我有这个代码:
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)
}
字符串
如果需要,我可以提供任何其他代码。如果没有我的其他代码和图像、元素、选择器等,这段代码并不能真正“运行”或做任何事情。我已经让localStorage使用以下代码工作:
dayTimer.innerHTML = `<p>You have taken ${dayCounter}/6 days!</p>`
dayTimer.class = "save-timer"
function saveDayTimer() {
localStorage.setItem("dayCounter", dayTimer)
}
型
这在我的代码中显示为0/6,当用户结束一轮时,从0 -> 1 -> 2等开始。
但由于我没有使用两个“选择器”,因为它是,不知道该怎么称呼,我不能弄清楚。我整个星期都在做这个项目,所以我的大脑有点混乱。当我运行这个并以“得分”“赢得”一轮时,它给了我这个错误。
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)
型
我理解这意味着它不是一个附加的HTML DOM元素,但由于我试图附加highScoreDivNew
,我认为这会起作用。我在SO上潜伏了一段时间,寻找这个问题的答案,也许这只是一个糊涂的大脑,但我似乎找不到任何适合这个问题的答案,或者我可以工作。
我主要是尝试用document.createElement创建一个新的变量,但据我所知,innerHTML应该在新的div元素中吗?MDN文档在. createElement上有点混乱。
我的目标是当玩家达到获胜状态时,动态地将高分元素插入到我的highScoreDiv中,这是一个当我按下按钮时出现的div。我不一定需要存储和检索它,只是显示它,所以我不使用json或jquery或诸如此类的语言来寻找答案,因为我还不知道这些语言。
代码完整性:Code link
2条答案
按热度按时间mklgxw1f1#
以下是不使用JSON的方法:
字符串
fcwjkofz2#
appendChild()方法将指定的元素作为元素的子元素追加。我为造成的混乱道歉。
要将高分附加到body中的特定div中,需要以该div为目标,然后使用appendChild()方法将新的高分元素附加为该div的子元素。
假设你的HTML中有一个id为“highScoreDiv”的div,你想在其中显示高分,你可以这样修改saveHighScore()函数:
字符串
确保你的HTML中有一个id为“highScoreDiv”的div,你想在这里显示高分。如果div不存在,你需要像这样在HTML中添加它:
型