推荐javascript简单模板

jquery老大写的。 


在模板里用类似jsp的语法写。可以减少大量使用+来拼接。且效率很高。 

使用方法: tmpl(模板html,json数据串) 

1. [图片] TM截图未命名.png    

2. [代码][JavaScript]代码     

01 // Simple JavaScript Templating
02 // John Resig - http://ejohn.org/ - MIT Licensed
03 (function(){
04 var cache = {};
05 this.tmpl = function tmpl(str, data){
06 // Figure out if we‘re getting a template, or if we need to
07 // load the template - and be sure to cache the result.
08 var fn = !/\W/.test(str) ?
09 cache[str] = cache[str] ||
10 tmpl(document.getElementById(str).innerHTML) :
11 // Generate a reusable function that will serve as a template
12 // generator (and which will be cached).
13 new Function("obj",
14 "var p=[],print=function(){p.push.apply(p,arguments);};" +
15 // Introduce the data as local variables using with(){}
16 "with(obj){p.push(‘" +
17 // Convert the template into pure JavaScript
18 str
19 .replace(/[\r\t\n]/g, " ")
20 .split("<%").join("\t")
21 .replace(/((^|%>)[^\t]*)‘/g, "$1\r")
22 .replace(/\t=(.*?)%>/g, "‘,$1,‘")
23 .split("\t").join("‘);")
24 .split("%>").join("p.push(‘")
25 .split("\r").join("\\‘")
26 "‘);}return p.join(‘‘);");
27 // Provide some basic currying to the user
28 return data ? fn( data ) : fn;
29 };
30 })();

3. [代码][JavaScript]代码     跳至 [2] [3] [全屏预览]

01 <script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script><script type="text/javascript">// <![CDATA[
02 $(document).ready(function(){
03     var json =
04         {
05             "key":"1",
06             "datas":
07                 [{"k":"v1","k2":"v2"}],
08             "test_if":true,
09             "test_for_datas":[1,2,3,4,5,6,7,8,9,10]
10         };
11     var tmp =     ‘key:<%=key%></br>‘+
12                 ‘datas:
13 <ul>
14     <li><%=datas[0].k%></li>
15     <li><%=datas[0].k2%></li>
16 </ul>
17 ‘+
18                 ‘test_if:‘+
19                 ‘<%if(test_if){%>‘+
20                 ‘成立‘+
21                 ‘<%}else{%>‘+
22                 ‘失败‘+
23                 ‘<%}%>‘+
24                 ‘</br>‘+
25                 ‘循环:‘+
26                 ‘<%for(var i=0;i<test_for_datas.length;i++){%>‘+
27                     ‘<%=test_for_datas[i]%>‘+
28                 ‘<%}%>‘;
29     $("#conent").html(tmpl(tmp,json));
30 });
31 // ]]></script>

推荐javascript简单模板,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。