测验得分变量在测验完成后不会更新



我正在制作一个JS问答应用程序,除了一件事外,所有功能都已关闭。当用户完成测试后,最新的分数不会更新,只会继续显示给出的第一个分数。这影响了向用户显示正确分数的能力,也阻止了将新分数添加到排行榜中。这是一个相当大的项目,有多个文件。所以有很多东西要粘贴到堆栈中。

我想给出一个文件结构的布局,使其尽可能容易理解:

用户从主页开始,主页由index.htmlstyle.cssscript.js组成。对用户来说,这是两个按钮的选择:播放按钮和高分按钮。

播放按钮转到game.htmlgame.css,并且仍然使用script.js并且这是游戏发生的文件。

highcores按钮使用highcores.htmlHighcore.csshighcore.js。此页面使用js-dom操作从本地存储添加highcores,将它们放在列表中供用户查看并返回。

结束页是在测验结束后向用户显示的内容。在这里,用户会被提示输入自己的姓名以保存刚刚收到的分数,然后将其保存到排行榜中。此页面使用end.htmlstyle.cssend.js.

我相信问题出在highcores.js/html/strong>或end.js/html/strong]的通信上。所以我把这四个文件放在这里,请随时寻求其他需要的人。但我真的很感谢你的帮助!

为了获得高分,你必须通过以下测试:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Quiz Project</title>
<link rel="stylesheet" href="./assets/style.css">
</head>
<body>
<div class="container">
<div id="home" class="flex-column flex-center">
<h1>Good Luck!</h1>
<a href="./game.html" class="btn">Play</a>
<a href="./highscores.html" class="btn" id="highscores-btn">Highscores</a>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"> 
</script>
<script src="./assets/script.js"></script>

这是游戏页面的HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Good Luck!</title>    
<link rel="stylesheet" href="./assets/style.css">
<link rel="stylesheet" href="./assets/game.css">
</head>
<body>
<div class="container">
<div id="game" class="justify-center">
<div id="hud">
<div class="hud-item">
<!-- container desc -->
<p id="container-text" class="hud-prefix">
Question:
</p>
<!-- timer function -->
<div id="timer">
<h1 id="time-text">90</h1>
</div>
<!-- end of timer -->
</div>
<div class="hud-item">
<p class="hud-prefix">
Score:
</p>
<h1 class="hud-main-text" id="score">
0
</h1>
</div>
</div>
<h1 id="question">*question section placeholder*</h1>
<!-- making possible answers to given question -->
<div class="choice-container">
<p class="choice-prefix">A</p>
<p class="choice-text" data-number="1">Choice 1</p>
</div>
<!-- making possible answers to given question -->
<div class="choice-container">
<p class="choice-prefix">B</p>
<p class="choice-text" data-number="2">Choice 2</p>
</div>
<!-- making possible answers to given question -->
<div class="choice-container">
<p class="choice-prefix">C</p>
<p class="choice-text" data-number="3">Choice 3</p>
</div>
<!-- making possible answers to given question -->
<div class="choice-container">
<p class="choice-prefix">D</p>
<p class="choice-text" data-number="4">Choice 4</p>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="./assets/script.js"></script>

主屏幕和游戏屏幕的js

const question = document.getElementById('question');
const choices = Array.from($('.choice-text'));
const scoreText = document.getElementById('score');
//defining let var which values will change throughout the game
let currentQuestion = {};
let acceptingAnswers = true;
let score = 0;
let questionCounter = 0;
let availableQustions = [];
//defining list of potential questions to be called apon by currentQuestions
let questions = [
{
question: 'What types of variables can you define?',
choice1: 'var',
choice2: 'let',
choice3: 'const',
choice4: 'all of the above',
answer: '4'
},
// question 1 ^^^^
{
question: 'How would you store an item to local storage?',
choice1: 'localStorage.getItem()',
choice2: 'localStorage.setItem()',
choice3: 'localStorage.store()',
choice4: 'localStorage.setLocal()',
answer: '2'
},
// question 2 ^^^^
{
question: 'Inside which HTML tag do we write JS code?',
choice1: '<script>',
choice2: '<jscript>',
choice3: '<scripting>',
choice4: '<javascript>',
answer: '1'
},
// question 3 ^^^^
{
question: 'What is the correct JavaScript syntax to change the content of a <p> 
in HTML document?',
choice1: 'document.getElement("p").innerHTML = "Hello World"',
choice2: '(p).innerHTML = "Hello World"',
choice3: 'getElement("p").value = "Hello World"',
choice4: 'document("p").innerHTML = "Hello World"',
answer: '1'
},
// question 4 ^^^^
{
question: 'How would you write "Hello World" in an alert box?',
choice1: 'msgBox("Hello World");',
choice2: 'message("Hello World");',
choice3: 'alertBox("Hello World");',
choice4: 'alert("Hello World");',
answer: '4'
},
// question 5 ^^^^
{
question: 'How do you create a function?',
choice1: 'function:myFunction()',
choice2: 'function = myFunction()',
choice3: 'function myFunction()',
choice4: 'var function.value() = myFunction()',
answer: '3'
},
// question 6 ^^^^
{
question: 'How do you write an "if" statement?',
choice1: 'if = i == 5',
choice2: 'if (i == 5)',
choice3: 'if i == 5 then',
choice4: 'if i = 5',
answer: '2'
},
// question 7 ^^^^
{
question: 'How do you make a comment in JavaScript?',
choice1: '/*example*/',
choice2: '<!--example-->',
choice3: '//example',
choice4: '`example`',
answer: '3'
},
// question 8 ^^^^
{
question: 'What is the correct way to make an array?',
choice1: 'var colors = ["red", "green", "blue"]',
choice2: 'var colors = ("red", "green", "blue")',
choice3: 'var colors = {"red", "green", "blue"}',
choice4: 'var colors = "red", "green", "blue"',
answer: '1'
},
// question 9 ^^^^
{
question: 'JavaScript is a ____-side programming language.',
choice1: 'Client',
choice2: 'Server',
choice3: 'Both',
choice4: 'None',
answer: '3'
},
// question 10 ^^^^
]

//start game functionality and needed var
const SCORE_POINTS = 100;
const MAX_QUESTIONS = 10;
startGame = () => {
questionCounter = 0;
score = 0;
availableQustions = [...questions];
getNewQuestion();
}
//get new question function supplies new q when previous gets answered
getNewQuestion = () => {
if(availableQustions.length === 0 || questionCounter > MAX_QUESTIONS) {
localStorage.setItem('mostRecentScore', score)
return window.location.assign('./end.html')
}
questionCounter++
//making random question appear
const questionIndex = Math.floor(Math.random() * availableQustions.length)
currentQuestion = availableQustions[questionIndex]
question.innerText = currentQuestion.question
//was originally choices.array.forEach
choices.forEach((choice)=> {
const number = choice.dataset['number'];
choice.innerText = currentQuestion['choice' + number];
});
availableQustions.splice(questionIndex, 1);
acceptingAnswers = true;
}
choices.forEach(choice => {
choice.addEventListener('click', e => {
if (!acceptingAnswers) return
acceptingAnswers = false
const selectedChoice = e.target
const selectedAnswer = selectedChoice.dataset['number']
let classToApply = selectedAnswer == currentQuestion.answer ? 'correct' : 
'incorrect'
//if answer is correct add 100 to score
if (classToApply === 'correct') {
incrementScore(SCORE_POINTS)
} else {
//timer time will be subtracted by 10 if question is answered incorrectly
timerSec -= 10;
}
selectedChoice.parentElement.classList.add(classToApply)
setTimeout(() => {
selectedChoice.parentElement.classList.remove(classToApply)
getNewQuestion();
}, 1000)
})
});
//increment score funt and calling start game
incrementScore = num => {
score +=num
scoreText.innerText = score
}
startGame();

//timer funct for 90 sec
var timerSec = 90;
var timerText = document.getElementById('time-text')
var timer;
timer = setInterval(function() {
timerSec--;
timerText.textContent = timerSec
//if timer is less than or = to 0 the game will end
if (timerSec <= 0) {
clearInterval(timer);
return window.location.assign('./end.html');
//if there is no available q's and the timer is greater than 0 game will end
}if (availableQustions === 0 && timerSec > 0) {
clearInterval(timer);
return window.location.assign('./end.html');
}
},1000)

作为提醒;上面的部分并不是令人担忧的原因,我只是希望你能够了解该应用程序的全部功能。目前,这是创建mostCentreScore变量并将其存储到本地的唯一方法。下面的代码是与prolem相关联的js文件的HTML。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Good Job!</title>
<link rel="stylesheet" href="./assets/style.css">
</head>
<body>
<div class="container">
<div id="end" class="flex-center flex-column">
<h1 id="final-score">0</h1>
<form action="" id="end-form-container">
<h2 id="end-text">Enter your name below in order to save your score. 
</h2>
<input type="text" name="name" id="username" placeholder="Enter your 
name">
<button class="btn" id="save-score-btn" type="submit" 
onclick="saveHighScore(event)" >Save</button>
</form>
<a href="./game.html" class="btn">Play Again?</a>
<a href="./index.html" class="btn">Home</a>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"> 
</script>
<script src="./assets/end.js"></script>
</html>

这是高芯部分:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Highscores</title>
<link rel="stylesheet" href="./assets/style.css">
<link rel="stylesheet" href="./assets/highscores.css">
</head>
<body>
<div class="container">
<div class="container">
<div id="highscores" class="flex-center flex-column">
<h1 id="final-score">Leaderboard</h1>
<ul id="high-scores-list"></ul>
<a href="./index.html" class="btn">Go Home</a>
</div>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> 
</script>
<script src="./assets/highscores.js"></script>
</html>

现在来谈谈让我头疼的部分。这是end.js

const username = document.querySelector('#username')
const saveScoreBtn = document.querySelector('#save-score-btn')
const finalScore = document.querySelector('#final-score')
const mostRecentScore = localStorage.getItem('mostRecentScore')
const highScores = JSON.parse(localStorage.getItem('highScores')) || []
const MAX_HIGH_SCORES = 1000
finalScore.innerHTML = mostRecentScore

saveHighScore = e => {
e.preventDefault()
const score = {
score: mostRecentScore,
name: username.value
}
highScores.push(score)
highScores.sort((a,b) => {
return b.score - a.score
})
highScores.splice(10)
localStorage.setItem('highScores', JSON.stringify(highScores))
window.location.assign('./highscores.html')
}

highcores.js

const highScoresList = document.querySelector('#high-scores-list')
const highScores = JSON.parse(localStorage.getItem('highScores')) || []
highScoresList.innerHTML = highScores.map(score => {
return `<li class="high-score">${score.name} - ${score.score}</li>`
}).join('')

很抱歉对希望是一个简单的解决方案做了很长的解释。请告诉我是否需要任何编辑,或者是否有后续问题我可以回答。

感谢所有潜在的帮助!

您可以使用chrome中的开发工具来查看游戏结束时应用程序正在做什么,并且最终分数应该更新。您应该能够调试您的应用程序并找出故障所在。

最新更新