如何在没有框架的情况下制作和使用 HTML 中的模板
How to make and use a template in HTML without a framework
如果我要进行测验,其中所有问题都需要具有相同的格式,并且一次只能向用户显示 1 个问题,如果不进行复制和粘贴,我将如何做到这一点代码?我可以做一个模板吗?那将是我的首选。
提前谢谢你。
如果您只想一次显示一个问题,您可以使用 JavaScript 获取问题的文本元素和选项,并通过以下问题进行更改。
您还可以通过 JavaScript 或另一个 HTML 文件生成模板,在需要时使用 document.write() or 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>
如果我要进行测验,其中所有问题都需要具有相同的格式,并且一次只能向用户显示 1 个问题,如果不进行复制和粘贴,我将如何做到这一点代码?我可以做一个模板吗?那将是我的首选。
提前谢谢你。
如果您只想一次显示一个问题,您可以使用 JavaScript 获取问题的文本元素和选项,并通过以下问题进行更改。
您还可以通过 JavaScript 或另一个 HTML 文件生成模板,在需要时使用 document.write() or 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>