javascript - 如何使用 Handlebars 将输入名称属性设置为等于变量?

标签 javascript jquery handlebars.js

我是 Handlebars.js 的新手,我正在尝试弄清楚如何根据 JS 中定义的变量来设置单选按钮上的名称属性。

下面的代码当前给出了我想要的输出,除了我想根据变量的值将 name 属性设置为不同的名称。例如,如果变量编号设置为 4,我希望所有输入的名称均为“answer4”。

一些额外的背景信息:number 变量被设置为 quiz 函数中的参数,即 quiz("quizJSONFile", number);我使用数字来定义要附加测验问题和答案的 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
}];

最佳答案

我发现要做到这一点,我需要将变量带入包含 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));
    };

关于javascript - 如何使用 Handlebars 将输入名称属性设置为等于变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33470431/

相关文章:

javascript - 带有日期时间选择器的可编辑数据网格

javascript - 用于进行圆形选择的 jQuery 插件

Handlebars 中的变量

javascript - 带有页眉页脚 Angular ionic 的列表卡

javascript - 未使用的 div 出现在 React 谷歌地图上,我无法设置它的样式

javascript - 如何从哈希数据中删除 # 符号?查询?

javascript - 部分切换在 WordPress 中隐藏和显示

handlebars.js - 在Sendgrid Design模板中,如何使用表格的 Handlebars 迭代?

facebook - 如何使用 AngularJS、Mustache、Handlebars 等客户端模板引擎制作 Facebook Open Graph 友好元标记

javascript - Polymer 元素和 AngularJS 指令有什么区别?