![](/img/trans.png)
[英]When building a quiz app in Javascript how can I one question to the next?
[英]Javascript quiz: Cannot activate next question when next button is clicked
我剛剛開始學習 Vanilla JS,我正在使用 API 進行測驗,我需要你的幫助!
我希望能夠單擊“下一步按鈕”並出現下一個問題,但我無法訪問 API 問題。
希望這是有道理的。 如果需要進一步說明,請告訴我! 謝謝!
let apiUrl = " https://opentdb.com/api.php?amount=150"; function showQuestion(response) { console.log(response); console.log(response.data.results[0].question); let question = document.querySelector("#question"); question.innerHTML = response.data.results[0].question; } axios.get(apiUrl).then(showQuestion); function showNextQuestion(response) { console.log(response.data.results); } function nextQuestion() { let apiUrl = " https://opentdb.com/api.php?amount=150"; axios.get(apiUrl).then(showNextQuestion); } let nextButton = document.querySelector("#next"); nextButton.addEventListener("click", nextQuestion);
<,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" /> <script src="https.//unpkg.com/axios/dist/axios.min.js"></script> <link rel="stylesheet" href="/Users/adi/Desktop/SheCodes Resources/Quiz Game/style:css" /> <title>Document</title> </head> <body> <h1>Quiz</h1> <h2> Question? <div class="question" id="question">What is your name.</div> </h2> <span></span><button id="next">Next</button></span> <button id="answerButton">Answer</button> <h3 id="answer">Adodoola</h3> <script src="/Users/adi/Desktop/SheCodes Resources/Quiz Game/app4.js"></script> </body> </html>
打電話后
axios.get(apiUrl).then(showQuestion);
你有 150 個問題。 只需將結果存儲到 function
let questions = [];
axios.get(apiUrl).then(function(response) {
questions = response.data.results;
});
然后添加全局計數器
let questionIndex = 0;
並與之合作
function showNextQuestion() {
console.log(questions[questionIndex]);
}
function nextQuestion() {
questionIndex++;
showNextQuestion();
}
結果:
let apiUrl = " https://opentdb.com/api.php?amount=150";
let questions = [];
let questionIndex = 0;
axios.get(apiUrl).then(function(response) {
questions = response.data.results;
});
function showQuestion() {
let question = document.querySelector("#question");
question.innerHTML = questions[questionIndex];
}
function nextQuestion() {
questionIndex++;
showQuestion();
}
let nextButton = document.querySelector("#next");
nextButton.addEventListener("click", nextQuestion);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.