2012-03-22 6 views
1

私はいくつかのデータを入力した後、追加する前に追加しようとしているシンプルなテンプレートを持っていますが、動作を停止するようです。ここ特定のIDを持つdivにテンプレートを追加する方法はありますか?

jsfiddle

とコードです:

<ul class="wall_message"> 
    <li id="168" class="msgid"> 
     <div id="commentbox2"> 
     </div> 
    </li> 
    <!-- in this case the json will be added only before `commentbox2`--> 
    <li id="168" class="msgid"> 
     <div id="commentbox3"> 
     </div> 
    </li> 
</ul> 




<script id="comment" type="text/x-handlebars-template"> 
       {{#each this}} 
         <div class="commentsp">{{comment}}</div> 
       {{/each}} 
</script> 


<script> 

//right now this json has only one main key (5), but it could have more 
var data = {"5": 
      {"id":"2", "comment":"xxxxxxxx"} 
      } 

/initiate the template 
var template = Handlebars.compile($('#comment').html()); 

// place the json data in the template. the template will iterate through 
msg = template(data); 

jQuery.each(data, function(i, val) { 
    console.log(val.id) 

    //find the div with commentbox2 and add the msg before 
    $('div#commentbox'+val.id).before(msg); 
}); 
</script> 

イムわからない私は、この場合、間違ってやっているものを。

ありがとうございました

答えて

0

私はあなたの問題を解決しようとしました。

あなたのJsonは私にとって「ハンドルバー互換」ではないようです。 私は{{#each}}ステートメントで使用されるルート要素でそれを書き換えました。

var data = { 
    'items': [ 
     {"id":"2", "comment": "xxxxxxxx"}, 
     {"id":"3", "comment": "yyyyyyy"} 
    ] 
}; 

var template = Handlebars.compile($('#comment').html()); 
var msg = template(data); 

jQuery.each(data.items, function(i, val) { 
    $('div#commentbox'+val.id).before(msg); 
}); 

私はそれはあなたが望むものを願っていますここでhttp://jsfiddle.net/nsvT3/11/

を完全なデモを参照してください。

+0

私にテストさせてください。私は同様にルート要素を追加することができます。これは数分かかるかもしれない – Patrioticcow

+0

このhttp://jsfiddle.net/patrioticcow/nsvT3/15/を見てください。この場合、item.id.2はcommentbox2とitem.id.3にコメントボックス3に行く必要があります – Patrioticcow

+0

多分 'msg = template(val);'はループの中にあるはずです – Patrioticcow

関連する問題