2
我是Handlebars.js的新手,我想知道如何在單選按鈕上的名稱屬性基於我的JS中定義的變量。如何使用把手將輸入名稱屬性設置爲等於變量?
下面的代碼目前給出我想要的輸出,除了我想根據變量的值將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
}];