1.假设的数据,基础部分。
<div id="list1"></div> <script type="text/tmp" id="tmp5"> {{for}} <li>id:{{:ID}} name:{{:Name}}</li> {{/for}} </script>
var arr = [ { ID: 1, Name: "tom" }, { ID: 2, Name: "jack" }, { ID: 3, Name: "lucy"} ]; var html = $("#tmp5").render(arr); $("#list1").html(html);
2.jsrender中form和if判断。数据循环中,这是赋值:
$(".table2").append($("#tmp2").render(item.rankingList));
<table border="1" class="table2"> <tr> <td>Data1</td> <td>Data2</td> <td>Data3</td> <td>Data4</td> <td>Data5</td> <td>Data6</td> </tr> <!-- <div id="list2"></div>--> <script type="text/tmp" id="tmp2"> {{for #data}} <tr> <td>{{:#getIndex()+1}}</td><!--排行的个数--> <td>{{:activityUserNumber}}</td> <td>{{:nickname}}</td> <td>{{:numberSum}}</td> <td><p>my name is : {{:nickname}}</p> <p> {{if numberSum>100}} 入选 {{else}} 未入选 {{/if}} </p> </td> </tr> {{/for}} </script> </table>
var activityId="79479680213712896"; $.ajax({ type: "GET", url:"http://voteapi.51odear.com/wx/worksDetail/Ranking?activityId="+ activityId, dataType:'json', success: function(data){ var item=data.data; console.log(item.rankingList) $(".table2").append($("#tmp2").render(item.rankingList)); /* $("#list2").html($("#tmp2").render(item.rankingList));*/ },error:function (msg) { alert("error"+JSON.stringify(msg)); } });
3.分离for,此处使用 tmpl=“#xx”。这个是分离的script的id值~即可。hobbies此处是隐藏
<script type="text/tmp" id="tmp2"> {{for #data}} <tr> <td>{{:#getIndex()+1}}</td><!--排行的个数--> <td>{{:activityUserNumber}}</td> <td>{{:nickname}}</td> <td>{{:numberSum}}</td> <td>{{for tmpl="#tmp3" /}}</td> <td>{{for hobbies tmpl="#tmp3"/}}</td><!--hobbies此处是隐藏--> </tr> {{/for}} </script> </table> <script type="text/tmp" id="tmp3"> <p>my name is : {{:nickname}}</p> <p>我是: {{if numberSum>100}} 入选 {{else}} 未入选 {{/if}} </p> </script>