我似乎在本地存储上出错并且正在获取响应。投币方面的工作非常完美。我希望用户输入他们的名字,将他们的名字存储为本地存储,并在按下提交按钮时,页面使用他们的名字显示问候语。我的任务要求将其作为本地存储进行。谢谢!
<!DOCTYPE html>
<html>
<head>
<title>Heads or Tails</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<form>
What is your name: <input type="text" class="instructions" />
<input type="text" id="name" style="display: none;" />
<button type="button" class="submit" onclick="greeting();" >Submit</button>
</form>
<div class="hello"></div>
<h1>Will it be heads or tails?</h1>
<input type="button" class="button" onclick="junction();" value="Let's
Flip!">
<h3 id="response"></h3>
</body>
<script src="app.js"></script>
</html>
/*
Generate randomly 1 or 2
assign 1 to heads
use if else statement
else (number is 2) assign to tails
track results
make button clickable multiple times without refresh
*/
/* Heads or tails*/
function junction(){
var randomNumber = Math.floor(Math.random() * 2) + 1;
if(randomNumber == 1){
document.getElementById("response").innerHTML = "Heads!";
} else {
document.getElementById("response").innerHTML = "Tails!";
}
}
/*local storage of name*/
function greeting(){
var name= getElementById('name').value;
localStorage.setItem("userName", "name");
document.write.innerText = "Hello," + localStorage.getItem('userName')+
"let's play heads or tails!";
}
答案 0 :(得分:0)
问题在于您正在传递name的值,但是错误地将其作为字符串而不是您具有的预定义变量传递,因为localStorage.setItem("THE_NAME_OF_THE_SAVED_ITEM", THE_VALUE)
因此,这应该可以解决问题:
<!DOCTYPE html>
<html>
<head>
<title>Heads or Tails</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<form>
<!-- Few changes made here. -->
<label for="name">What is your name: </label>
<input type="text" id="name" placeholder="Enter name here...">
<button type="button" class="submit" onclick="greeting();" >Submit</button>
</form>
<h3 id="greetUser"></h3>
<div class="hello"></div>
<h1>Will it be heads or tails?</h1>
<input type="button" class="button" onclick="junction();" value="Let's
Flip!">
<h3 id="response"></h3>
</body>
<script>
/*
Generate randomly 1 or 2
assign 1 to heads
use if else statement
else (number is 2) assign to tails
track results
make button clickable multiple times without refresh
*/
/* Heads or tails*/
function junction(){
var randomNumber = Math.floor(Math.random() * 2) + 1;
if(randomNumber == 1){
document.getElementById("response").innerHTML = "Heads!";
} else {
document.getElementById("response").innerHTML = "Tails!";
}
}
/*local storage of name*/
function greeting(){
var name = document.getElementById('name').value;
var greetUser = document.getElementById("greetUser");
// Just get rid of the "" at the value (change "name" to name).
localStorage.setItem("userName", name);
greetUser.textContent = "Hello," + localStorage.getItem('userName') +
" . Let's play heads or tails!";
}
</script>
</html>
此外,也不完全确定要在何处显示来自document.write.innerText = "Hello," + localStorage.getItem('userName')+
"let's play heads or tails!";
的消息,但对我来说,当我在开发工具中尝试该部分时,它只是控制台登录,因此请在控制台中查找。