在这个简单的测验应用程序中,有一个下一个问题按钮。通过单击开始游戏按钮开始游戏后,将显示带有答案的第一个问题。单击下一个问题按钮时,仅在第二次单击第二个问题之后,第一个问题和答案仍然可见。在后台,尽管第二个问题针对的是第一次点击,但仅不可见。尝试了几种可能的解决方案,但没有一个可行。
// Methods part of ES6 class Question
displayQuestion() {
document.querySelector('.question').textContent = this.question
let i = 0
let answer = this.answers
for(let el of answer){
let html = `<li class="name" id=${i}>${el}</li>`
document.querySelector('ul').insertAdjacentHTML('beforeend',html)
i++
}
}
getAnswer(id){
if(id == this.correct) {
//console.log('Hooray!')
document.querySelector('.modal1').style.display = "flex";
document.querySelector('.modal').style.display = "block";
}else{
//console.log('Wrong answer!')
document.querySelector('.modal2').style.display = "flex";
document.querySelector('.modal').style.display = "block";
}
}
}
const questions = [q1, q2, q3, q4, q5];
let runningQuestion;
let gamePlaying;
init()
document.querySelector('.button1').addEventListener('click', nextQuestion)
function nextQuestion() {
if(gamePlaying && runningQuestion <= questions.length - 1){
clearAnswers()
document.querySelector('.button1').textContent = 'Next Question'
questions[runningQuestion].displayQuestion()
questions[runningQuestion].displayAnswers()
runningQuestion++
}
if(runningQuestion >= questions.length){
document.querySelector('.button1').textContent = 'Try again!'
runningQuestion = 0
}
}
document.querySelector('.answers').addEventListener('click', possibleAnswers)
function possibleAnswers(e){
console.log(e.target)
if(e.target && e.target.matches("li.name")){
let item = e.target.id
let id = parseInt(item)
questions[index].getAnswer(id)
}
}
function init() {
clearAnswers()
document.querySelector('.question').textContent = ""
gamePlaying = true
runningQuestion = 0
questions[runningQuestion].displayQuestion()
questions[runningQuestion].displayAnswers()
}
答案 0 :(得分:0)
疯狂猜测
if(gamePlaying) {
clearQuestion()
clearAnswers()
questions[index].displayQuestion()
index++
}
我认为您应该增加索引,然后调用函数。
index++
questions[index].displayQuestion()
答案 1 :(得分:0)
您可以使用此代码获取点击次数,并用if (clicks >= 2)
进行其余操作
var clicks = 0;
function myFunction() {
clicks += 1;
console.log(clicks)
}
<input type="button" onclick = "myFunction()" />