javascript - Handlebars ,访问每个循环变量的父级

标签 javascript html node.js handlebars.js

我有像这里这样的代码。我想将输入名称设置为来自之前每个循环的@index。

我可以通过某种方式访问​​@previousIndex 吗?或者我可以将输入分配给在第二个循环之前创建的某种组,该组将在其中设置所有输入名称吗?

我收到的数据:

 questions:[  
  {  
     question:"How old are you?",
     answers:[  
        '16',
        '18',
        '20',
        '25',
        'other'
     ]
  },
  {  
     question:"How many kids do you have?",
     answers:[  
        '0',
        '1',
        '2',
        'other'
     ]
  }
]

hbs代码:

{{#each questions}}
    <li>
        <h3 class='question'>{{this.question}}</h2>
        <div class='flexbox'>
            {{#each this.answers}}
            <label class="container">
                <input type='radio' name='{{@previousIndex}}' value='{{@index}}'>  
                <span class='checkmark'>{{this}}</span>
            </label>              
            {{/each}}
        </div>
    </li>
{{/each}}

最佳答案

当你使用#each 时,你会在 @index 中得到索引,如果你想要 previousIndex 为什么不直接使用 parseInt(@index) - 1

这是你如何做的:

var Handlebars = require('handlebars');

Handlebars.registerHelper("previous", function(value, options)
{
    return parseInt(value) - 1;
});

现在将您的 hbs 代码更新为:

{{#each questions}}
    <li>
        <h3 class='question'>{{this.question}}</h2>
        <div class='flexbox'>
            {{#each this.answers}}
            <label class="container">
                <input type='radio' name='{{previous @index}}' value='{{@index}}'>  
                <span class='checkmark'>{{this}}</span>
            </label>              
            {{/each}}
        </div>
    </li>
{{/each}}

希望这对你有用!

关于javascript - Handlebars ,访问每个循环变量的父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52135764/

相关文章:

javascript - ReactJS - 使用 onBlur 验证电子邮件字段

javascript - 使用具有模态样式的 jQuery 插入 iFrame

javascript - Webpack/Node.js Http 模块 : http. createServer 不是函数

node.js - 如何将 node_modules 文件夹从 docker 容器中复制到构建机器上?

javascript - 如何使用javascript将iframe高度设置为100%

javascript - D3 : Cannot select an item based on its id

html - Flash 将影片剪辑与 HTML 混合

javascript - 获取位置为 :fixed 的元素的高度

javascript - Nodejs Express3 使用 session 检查用户是否登录

javascript - Angular JS UI-Router 如何在不重新加载页面的情况下更改导航栏中的 url