我尝试使用选项渲染一个select元素,比如
<select dropdown multiple class="dropdown" name="color">
{{#each colors}}
<option value="{{value}}" {{isSelected parentColor id}}>{{title}}></option>
{{/each}}
</select>
我使用以下把手助手
Handlebars.registerHelper('isSelected', function(input, color) {
return input === color ? 'selected' : '';
});
问题是selected
属性没有出现在任何option
元素上,但是当我在把手助手中放置console.log
时,我确实看到了一个匹配(输入=== color === true)。我在这里做错了什么想法?
答案 0 :(得分:13)
这是所描述内容的一个实例,
<强> HBS 强>
<h1>Handlebars JS Example</h1>
<script id="some-template" type="text/x-handlebars-template">
<select dropdown multiple class="dropdown" name="color">
{{#each colors}}
<option value="{{value}}" {{isSelected parentColor id}}>{{title}}</option>
{{/each}}
</select>
</script>
<强> JS 强>
var source = $("#some-template").html();
var template = Handlebars.compile(source);
var data = {
colors: [
{id:1,value:1,title:"red",parentColor:2},
{id:2,value:2,title:"green",parentColor:2},
{id:3,value:3,title:"blue",parentColor:1}
]
};
Handlebars.registerHelper('isSelected', function (input, color) {
return input === color ? 'selected' : '';
});
$('body').append(template(data));