我是Handlebars.js的新手,我试图根据我在JS中定义的变量找出如何在单选按钮上使用name属性。
下面的代码当前给出了我想要的输出,除了我想根据变量的值将name属性设置为不同的名称。例如,如果变量编号设置为4,我希望所有输入的名称为' answer4'。
一些额外的背景信息:数字变量在测验函数中被设置为参数,即测验(" quizJSONFile",数字);我使用数字来定义哪些html元素可以附加测验问题和答案。
HTML:
<script id="radio-template" type="x-handlebars-template">
{{#each this}}
<input name='answer' type='radio' value='{{@index}}' >{{this}}<br>
{{/each}}
</script>
JS:
function createRadios(){
var radioScript = $("#radio-template").html();
var template = Handlebars.compile(radioScript);
$("#question").append(template(allQuestions[counter].choices));
};
JSON:
var allQuestions = [{
question: "How many presidents were members of the Whig party?",
choices: ["Four", "Three", "Two"],
correct: 0
}, {
question: "Who was the first president to be impeached?",
choices: ["Andrew Jackson", "Andrew Johnson", "Warren Harding"],
correct: 1
}, {
question: "How many presidents died during their presidency?",
choices: ["Four", "Six", "Eight"],
correct: 2
}, {
question: "How many presidents had no party affiliation?",
choices: ["One", "Two", "Three"],
correct: 0
}, {
question: "Who was the only president to serve two non-consecutive terms, making him both the 22nd and 24th president?",
choices: ["John Quincy Adams", "William Howard Taft", "Grover Cleveland"],
correct: 2
}];
答案 0 :(得分:0)
我想到要做到这一点,我需要将变量放在包含Handlebars编译器的函数中,即var quizNum = num;
HTML:
<script id="radio-template" type="x-handlebars-template">
{{#each this}}
<input name={{answerSet}} type='radio' value={{@index}} >{{this}}<br>
{{/each}}
</script>
JS:
function createRadios() {
var quizNum = num;
var radioScript = $("#radio-template").html();
var template = Handlebars.compile(radioScript);
Handlebars.registerHelper('answerSet', function () {
return "quiz" + quizNum;
});
question.append(template(allQuestions[counter].choices));
};