【发布时间】:2018-08-19 01:05:22
【问题描述】:
如果我要进行测验,其中所有问题都需要具有相同的格式,并且一次只能向用户显示 1 个问题,我将如何在不复制和粘贴代码的情况下做到这一点?我可以做一个模板吗?那将是我的首选。
先感谢您。
【问题讨论】:
标签: javascript jquery html templates templating
如果我要进行测验,其中所有问题都需要具有相同的格式,并且一次只能向用户显示 1 个问题,我将如何在不复制和粘贴代码的情况下做到这一点?我可以做一个模板吗?那将是我的首选。
【问题讨论】:
标签: javascript jquery html templates templating
如果您只想一次显示一个问题,您可以使用 JavaScript 获取问题的文本元素和选项,然后通过以下问题更改它们。
您还可以通过 JavaScript 或其他 HTML 文件生成模板,在需要时使用 document.write() 或 innerHTML 复制该模板。
如何做到这一点的小例子:
var questions = ["2 + 2", "1 + 3", "8 / 2", "5 - 2"];
var currentQuestion = 0;
var answers = [];
function nextQuestion() {
//Store answers:
var value = $("input[name=options]:checked").val();
answers.push(value);
console.log(answers);
//Next question:
currentQuestion++;
document.getElementById("question").innerHTML = questions[currentQuestion];
}
/* Apply your styles*/
#question {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="question">2 + 2?</div>
<form action="">
<input type="radio" name="options" value="5">5<br>
<input type="radio" name="options" value="4">4<br>
<input type="radio" name="options" value="3">3
</form>
<button onclick="nextQuestion()">next question</button>
【讨论】: