Javascript 把手,访问每个循环变量的父对象
我有这样的代码。我想从上一个循环中将输入名称设置为@index 我可以访问@previousIndex吗?或者我可以将输入分配给在第二个循环之前创建的某种组,该循环将在其中设置所有输入名称 我收到的数据:Javascript 把手,访问每个循环变量的父对象,javascript,html,node.js,handlebars.js,Javascript,Html,Node.js,Handlebars.js,我有这样的代码。我想从上一个循环中将输入名称设置为@index 我可以访问@previousIndex吗?或者我可以将输入分配给在第二个循环之前创建的某种组,该循环将在其中设置所有输入名称 我收到的数据: questions:[ { question:"How old are you?", answers:[ '16', '18', '20', '25', 'other'
questions:[
{
question:"How old are you?",
answers:[
'16',
'18',
'20',
'25',
'other'
]
},
{
question:"How many kids do you have?",
answers:[
'0',
'1',
'2',
'other'
]
}
]
哈佛商学院代码:
{{#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}}
{{#每个问题}
{{这个问题}
{{{#每个人都这样回答}
{{this}}
{{/每个}}
{{/每个}}
我无法为您提供100%的工作代码(当前未设置环境),但根据我以前使用把手的经验,我将尝试为您提供一个可能的解决方案
{{assign "previousIndex" 0}}
{{#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>
{{assign "../previousIndex" "{{@index}}"}}
{{/each}}
{{assign“previousIndex”0}
{{{每个问题}
{{这个问题}
{{{#每个人都这样回答}
{{this}}
{{/每个}}
{{assign../previousIndex'{{@index}}}
{{/每个}}
当您使用#each时,您会在@index
中获得索引,如果您想要以前的索引,为什么不直接执行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}}
{{#每个问题}
{{这个问题}
{{{#每个人都这样回答}
{{this}}
{{/每个}}
{{/每个}}
希望这对你有用 我必须创建两个类似于这里的助手函数。Get之所以在这里,是因为我无法通过简单地写入{{myVariableName}直接从.hbs文件访问变量。 Hbs文件现在看起来像这里
<div class='flexbox'>
{{assign "parentIndex" @index }}
{{#each this.answers}}
<label class="container">
<input type='radio' name='{{get "parentIndex"}}' value='{{@index}}'>
<span class='checkmark'>{{this}}</span>
</label>
{{/each}}
</div>
也许这会对你有帮助这个问题解决了吗?检查下面的答案?它起作用了吗?我发布了我自己的答案。
assign: function(varName, varValue, options) {
options.data.root[varName] = varValue;
}
get: function(varName, options) {
return options.data.root[varName]
}