Javascript 使用把手助手/for循环,在文档中为每个标签写一次标题
我有一个对象数组,每个对象都有一个具有不同名称的属性“标记”。我使用手柄在一组问题中循环,并显示问题标题和每个问题的数据。每个标签都是按顺序排列的,这取决于它们有什么标签,我希望有一个标题,当标签属性是唯一的时,它会显示出来 我有点像:Javascript 使用把手助手/for循环,在文档中为每个标签写一次标题,javascript,handlebars.js,Javascript,Handlebars.js,我有一个对象数组,每个对象都有一个具有不同名称的属性“标记”。我使用手柄在一组问题中循环,并显示问题标题和每个问题的数据。每个标签都是按顺序排列的,这取决于它们有什么标签,我希望有一个标题,当标签属性是唯一的时,它会显示出来 我有点像: var questions = [ { title: 'This is the first question', tag: 'FirstTag' }, { title: 'This is the second question
var questions = [
{
title: 'This is the first question',
tag: 'FirstTag'
},
{
title: 'This is the second question',
tag: 'FirstTag'
},{
title: 'This is the third question',
tag: 'SecondTag'
}]
我在索引中循环遍历它们,想添加一个把手助手,如下所示:
{{#each this}}
{{display_tag}}
<h2>{{title}}</h2>
{{/each}}
{{{#每个this}
{{display_tag}}
{{title}}
{{/每个}}
我想尝试一些类似的方法,查找元素是否存在id,如果不存在:make it。如果有,就不要去了。但是我在这里写的代码只是让标签出现在每个问题之前
Handlebars.registerHelper('display_tag', function() {
if ($('#' + this.tag).length < 1) {
return new Handlebars.SafeString(
"<a id='" + this.tag + "'><h3>" + this.tag + "</h3></a>"
);
} else {
return false;
}
});
handlebar.registerHelper('display_tag',function(){
if($('#'+this.tag).length<1){
返回新把手。安全字符串(
“”+this.tag+“”
);
}否则{
返回false;
}
});
有什么线索吗?使用普通把手(无Ember.js)的解决方案非常相似: 模板:
{{#each this}}
{{#unless tagAlreadyUsed}}
<a id="{{tag}}"><h3>tag</h3></a>
{{/unless}}
<h2>{{title}}</h2>
{{/each}}
{{#each taggedQuestions}}
{{#unless tagAlreadyUsed}}
<a {{bind-attr id=tag}}><h3>tag</h3></a>
{{/unless}}
<h2>{{title}}</h2>
{{/each}}
模板:
{{#each this}}
{{#unless tagAlreadyUsed}}
<a id="{{tag}}"><h3>tag</h3></a>
{{/unless}}
<h2>{{title}}</h2>
{{/each}}
{{#each taggedQuestions}}
{{#unless tagAlreadyUsed}}
<a {{bind-attr id=tag}}><h3>tag</h3></a>
{{/unless}}
<h2>{{title}}</h2>
{{/each}}
{{{#每个标记问题}
{{{#除非tagAlreadyUsed}
标签
{{/除非}
{{title}}
{{/每个}}
谢谢你的评论,这是我的错,因为这里使用了ember.js标记,但实际上这不是一个ember项目。我只是在用把手。如果不使用控制器,这会是什么样子?这是相同的解决方案,您只需在其他地方执行映射逻辑。请参阅我的最新答案。