2012-08-06 113 views
0

我想根據部分數據集(JSON)在div上添加一個類。這是我 數據:手柄條件

{ 
    "title":"energy star", 

    "cat":"power", 

    "diff":"Investment", 
    "description":"When purchasing appliances, consider buying 'energystar' certified appliances to radically reduce the amount of electricity used by older appliances.", 
    "links":[ 
     { 
      "title":"The Official Website of Energystar", 
      "url":"http://www.energystar.gov" 
     } 
    ], 
    "cost":"$60+" 
}, 
{ 
    "title":"shut the faucet", 
    "cat":"water", 
    "diff":"No-Cost", 
    "description":"Turn off the water while you brush your teeth. There is never a good reason for waste.", 
    "cost":"$0" 
},` 

這裏是我的模板

 {{#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}} 

,這是我的助手功能

Handlebars.registerHelper("addClasses",function(){ 
    if(this.cat=="water"){ 
      console.log('water'); 
      $(".tip_whole").addClass("water"); 
     } else { 
      console.log('no water here'); 
     } 
});//end of helper function 

它正確地記錄,有水,但它永遠不會添加類,它只會影響硬編碼的'.tip_whole',但不會影響手柄創建的'.tip_whole'

+0

edit:formatting – alexdmejias 2012-08-06 12:56:41

回答

3

這個幫手不會工作,因爲.tip_whole不在DOM中,當你說$(".tip_whole"),所以你最終將你的water類添加到什麼都沒有。你將不得不改變你的助手返回一個類(或無)作爲一個字符串:

Handlebars.registerHelper("addClasses", function() { 
    return this.cat == 'water' ? 'water' : ''; 
}); 

,然後在您想要的類中使用該助手:

<div class="tip_whole {{addClasses}}"> 

演示:http://jsfiddle.net/ambiguous/SSPSY/