Javascript 车把中的条件句
我想根据我的部分数据集(JSON)在div上添加一个类。这就是我所拥有的 数据: 这是我的模板Javascript 车把中的条件句,javascript,css,templates,handlebars.js,Javascript,Css,Templates,Handlebars.js,我想根据我的部分数据集(JSON)在div上添加一个类。这就是我所拥有的 数据: 这是我的模板 {{#each this}} {{#addClasses}} {{/addClasses}} <div class="tip_whole"> <div class="tip_header"> <h5 class="tip_title">
{{#each this}}
{{#addClasses}}
{{/addClasses}}
<div class="tip_whole">
<div class="tip_header">
<h5 class="tip_title">
<b>{{title}}</b> - {{diff}}
</h5>
<div class="tip_social">
<a href=""><img src="IMG/media/twitter_16.png" alt="twiter link"/></a>
<a href=""><img src="IMG/media/facebook_16.png" alt="facebook link"/></a>
<a href=""><img src="IMG/media/email_16.png" alt="email link"/></a>
</div>
</div>{{!end .tip_title}}
<div class="tip_body">
<div class="grid_20 alpha">
<p class="tip_desc">{{description}}</p>
{{#if links}}
<div class="tip_links">
<h5>More information</h5>
{{#each links}}
<a href="{{url}}" class="tip_link" target="_blank">{{title}}</a>
{{/each}}
</div>{{!end .tip_links}}
{{/if}}
</div>{{!end .grid_20 alpha}}
<div class="grid_19 push_2">
<h2 class="tip_cost_title">Avg. Cost to Implement</h2>
<h1 class="tip_cost_title">{{cost}}</h1>
</div>
</div>{{!end .tip_body}}
</div>{{!end .tip_whole}}
{{/each}}
它会正确地记录有水,但不会添加类,它只会影响硬编码的“.tip\u-thill”,但不会影响由把手创建的那些助手,因为当您说“
$”(“.tip\u-thill”)时,.tip\u-thill
不在DOM中
因此,您最终将您的水
类添加为零。您必须更改助手以字符串形式返回类(或不返回任何内容):
Handlebars.registerHelper("addClasses", function() {
return this.cat == 'water' ? 'water' : '';
});
然后在需要类的位置使用该帮助器:
<div class="tip_whole {{addClasses}}">
演示:该助手将无法工作,因为当您说
$(“.tip\u-thill”)
时,.tip\u-thill
不在DOM中,所以您最终将water
类添加为空。您必须更改助手以字符串形式返回类(或不返回任何内容):
Handlebars.registerHelper("addClasses", function() {
return this.cat == 'water' ? 'water' : '';
});
然后在需要类的位置使用该帮助器:
<div class="tip_whole {{addClasses}}">
演示: