[英]Need to click button twice for event to fire
在這個簡單的測驗應用程序中有一個下一個問題按鈕。 通過單擊開始游戲按鈕開始游戲后,第一個帶有答案的問題會顯示。 單擊下一個問題按鈕時,第一個問題和答案仍然可見,只有在第二次單擊后才會出現第二個問題。 在后台,雖然第二個問題是針對第一次點擊的,但只是不可見。 嘗試了幾種可能的解決方案,但沒有一個有效。
// 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()
}
胡亂猜測
if(gamePlaying) {
clearQuestion()
clearAnswers()
questions[index].displayQuestion()
index++
}
我認為你應該增加索引,然后調用 function。
index++
questions[index].displayQuestion()
您可以使用此代碼獲取點擊次數,並使用if (clicks >= 2)
執行 rest
var clicks = 0; function myFunction() { clicks += 1; console.log(clicks) }
<input type="button" onclick = "myFunction()" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.