我有一个有效的javascript测验。目的是保存用户的分数。
这就是我所拥有的。在测验(quiz.html)结束时,弹出一个警报,并显示用户的分数(这工作很好)。关闭警告框后,将出现一个新窗口complete.html(这也起作用)。
var score = 0; // Default score is 0
if (questionIndex >= questions.length) {
alert("End of quiz! You scored " + score + " points!"); // alert user that time is up
window.open("./complete.html", "_self"); // open a new window
} else {
render(questionIndex);
}
在我的complete.html中,我有以下代码。
<div class="quizComplete">
<h2>All done!</h2>
<p>
Your score is:
<span id="quizTotalScore">
<!-- USER SCORE APPEARS HERE -->
</span>
</p>
</div>
但是,我尝试使用document.queryselector(“#quiztotalscore”).textContent=score;
,但是分数没有出现在SPAN#quiztotalscore中。我错过什么了吗?我是否需要先将分数保存在localStorage中,以便它出现在complete.html上?
使用LocalStorage/Cookie
在导航到下一页之前,在localStorage中设置一个变量
localStorage.setItem("score","value");
window.open("complete.html", "_self");
在第二页的窗口加载事件中。
$(function() {
if(localStorage.getItem("variable")) {
// set the ID here
// after setting remember to remove it, if it's not required
localStorage.removeItem("variable");
}
});