用template引擎可以解决在js中繁琐的拼接html的字符串问题
代码
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript" src="template.js"></script>
</head>
<body>
<div id="divText"></div>
</body>
<!-- 模板 -->
<script id="templateTest" type="text/template">
<% for(j in json){item=json[j]; %>
<% if(j==0){ %>
<div><%=item.text%>!!!!</div>
<% }else{ %>
<div><%=item.text%></div>
<% } %>
<% } %>
</script>
<script>
//需要遍历的对象
var json = [{
text:"Hello World"
},{
text:"Hello Template"
},{
text:"Hello Html"
}];
//加载模板
var str = template('templateTest', { //模板的id=templateTest
"json": json//传递的参数
});
document.getElementById("divText").innerHTML=str;
</script>
</html>
所需的js文件:template.js]
链接:https://pan.baidu.com/s/1Aer96TBK2_1qhWyy8YCkOg
提取码:xkjx