标签:var ret element rip div size type template document
/*
1.模板
2.解析,替换字符串
JavaScript模版引擎就是字符串替换,剥离出JavaScript语句,然后利用新的字符串构造函数,返回结果。
*/
<!DOCTYPE html> <html> <head> <title>Template</title> </head> <body> <div id="results"></div> <script type="text/html" id="user_tmpl"> <ul> <% for ( var i = 0; i < users.length; i++ ) { %> <li><a href="<%=users[i].url%>"><%=users[i].name%></a></li> <% } %> </ul> </script> <script> var results = document.getElementById("results"); var users=[ {"name":"smile", "url":"http://localhost"}, {"name":"Amy", "url":"http://localhost"}, {"name":"JavaScript", "url":"http://localhost"} ]; //模板解析 function tmpl(id,data){ //data:JSON对象。 var html=document.getElementById(id).innerHTML; var result="var p=[];with(obj){p.push(‘" +html.replace(/[\r\n\t]/g," ") .replace(/<%=(.*?)%>/g,"‘);p.push($1);p.push(‘") .replace(/<%/g,"‘);") .replace(/%>/g,"p.push(‘") +"‘);}return p.join(‘‘);"; var fn=new Function("obj",result); return fn(data); } results.innerHTML = tmpl("user_tmpl", users); </script> </body> </html>
效果图:
标签:var ret element rip div size type template document
原文地址:https://www.cnblogs.com/Longhua-0/p/9299189.html