我有像这里这样的代码。我想将输入名称设置为来自之前每个循环的@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/