我想在单击按钮 (onclick) 后显示此测验。此时它直接出现在网站中。我确信这很简单,但我被困在这里。你知道我应该如何添加按钮代码吗?
这里是 HTML:
<div id="quiz"></div>
这里是 JavaScript 测验:
(function() {
function buildQuiz() {
const output = [];
myQuestions.forEach((currentQuestion, questionNumber) => {
const answers = [];
for (letter in currentQuestion.answers) {
answers.push(
`<label>
<input type="radio" name="question${questionNumber}" value="${letter}">
${letter} :
${currentQuestion.answers[letter]}
</label>`
);
}
output.push(
`<div class="question"> ${currentQuestion.question} </div>
<div class="answers"> ${answers.join("")} </div>`
);
});
quizContainer.innerHTML = output.join("");
}
const quizContainer = document.getElementById("quiz");
const myQuestions = [{
question: "Who is the strongest?",
answers: {
a: "Superman",
b: "The Terminator",
c: "Waluigi, obviously"
},
correctAnswer: "c"
},
{
question: "What is the best site ever created?",
answers: {
a: "SitePoint",
b: "Simple Steps Code",
c: "Trick question; they're both the best"
},
correctAnswer: "c"
}
];
最佳答案
您可以做几件事来完成您想要的事情。这是我认为最好的方法。
- 将 buildQuiz 从无名函数调用中取出,使其成为一阶函数。这将使其他功能能够调用它。
创建一个事件监听器,其中包含您要使用的所有 javascript,它会在加载 DOM 内容后运行。看起来像这样:
document.addEventListener("DOMContentLoaded", function(event){ //DOM准备好后运行的代码 }
这将允许您的代码仅在 DOM 准备就绪时运行,并允许您组织代码的运行方式。
- 在前面提到的事件监听器中为您想要控制测验创建的按钮放置一个事件监听器。在此回调中将调用创建您的测验。
这是一个 codepen这说明了这是如何工作的。同样在您的真实情况中,包含一个 noscript 标签也很重要,以防该人在其浏览器上未启用 javascript。干杯!
关于javascript - 单击按钮后显示 javascript 测验,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48714021/