我创建了一个定时测验,将分数保存到本地存储中,但不保存用户输入的用户名。我将包含应用程序的最后一个 html 文档,分数是从游戏脚本文件中保存的。我认为我不需要编辑我的游戏脚本文件,因为分数确实保存到本地存储中。
//html代码如下
!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="assets/style.css">
<title>Congratulations</title>
</head>
<body>
<div class="container">
<div id="end" class="flex-center flex-column">
<h1 id="finalScore">0</h1>
<form>
<input
type="text name"
name="username"
id="username"
placeholder="username"/>
<button
type="submit"
class="btn"
id="submitBtn"
onclick>
Save
</button>
<a class="btn" href="game.html">Play Again</a>
<a class="btn" href="start.html">Go Home</a>
</form>
</div>
</div>
<script src="assets/end.js"></script>
</body>
</html>
下面的 JavaScript 代码 - 我对我在代码中计划的内容有评论。
//links username from end html doc
const usernameInput = document.getElementById('username');
//links save socre button from html doc
const submitBtn = document.getElementById('submit');
//links the final score
const finalScore = document.getElementById('finalScore');
//retrieves the end score from local storage
const mostRecentScore = localStorage.getItem('mostRecentScore');
//pulls most recent score from game script and saves it to end screen
finalScore.innerText = mostRecentScore;
submitBtn.addEventListener('click', function(event) {
//keeps entry form being entered into the url
event.preventDefault();
var username = document.querySelector("#username").value;
//turn array entry into a string
localStorage.setItem('username', username);
});
我尝试创建的应用程序出现错误。玩家的用户名不会保存到本地存储中。
您使用
document.getElementById('submit')
来抓取提交按钮。但在您的 HTML 文件中,提交按钮的 id
是 submitBtn
而不是 submit
。所以,你必须使用 submitBtn
而不是 submit
。
在JS中,代码将是-
const submitBtn = document.getElementById("submitBtn");