html:
<div class="box"></div>
<script id="t1" type="text/html">
{{each xiaolei as index}} //循环采用each as 循环,xiaolei 为循环体,在js里面有定义 。
<dd>
<div class="picture">
<img src="{{index.picture}}" />
</div>
<div class="dishes">
<p class="dish_title">{{index.name}}</p>
<div class="under_dishes">
<div class="under_content">
<p class="sales">月售{{index.monthSale}}</p>
<p class="price">¥<span>{{index.price}}</span></p>
</div>
<p class="add"> <i class="icon iconfont icon2"></i> <span class="nums"> 1 </span> <i class="icon iconfont icon1"></i> </p>
</div>
</div>
</dd>
{{/each}}
</script>
js:
//ajax请求json数据 function rightDataRender(smallClassfy){ var html=""; var xiaolei; //var classfyArray; $.ajax({ //ajax请求 url:"js/orderMeal.json", type:"get", dataType:"json", async:true, data:{}, error:function(){ console.log("对不起,请求出错!"); }, success:function(data){ //如果请求成功,根据条件定义xiaolei switch(smallClassfy){ case 0:xiaolei=data.recommend; break; case 1:xiaolei=data.specialtyCoffee; break; case 2:xiaolei=data.tea; break; } console.log(xiaolei); var xiaoleit1 =template("t1",{xiaolei:xiaolei}); //模板渲染 $(".box").html(xiaoleit1); } }) }
基本的模板渲染就是这些,如果不用template模板,则用字符串拼接是这样的:
for(var i=0;i<xiaolei.length;i++){
html+='<dd>'
+ '<div class="picture">'
+ '<img src=" '+xiaolei[i].picture+' " />'
+ '</div>'
+ '<div class="dishes">'
+ '<p class="dish_title">'+xiaolei[i].name+'</p>'
+ '<div class="under_dishes">'
+ '<div class="under_content">'
+ '<p class="sales">月售'+xiaolei[i].monthSale+'</p>'
+ '<p class="price">¥<span>'+xiaolei[i].price+'</span></p>'
+ '</div>'
+ '<p class="add"> <i class="icon iconfont icon2"></i> <span class="nums"> 1 </span> <i class="icon iconfont icon1" οnclick="addFun()" ></i> </p>'
+ '</div>'
+ '</div>'
+'</dd>';
$(".box").html(html);
}
其实两者效果差不多,不过稍有不同,知识在于总结哈!
不过模板渲染要引入 template-web.js 文件,可以在官网下载。