推荐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(){
04var cache = {};
05this.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.
08var fn = !/\W/.test(str) ?
09cache[str] = cache[str] ||
10tmpl(document.getElementById(str).innerHTML) :
11// Generate a reusable function that will serve as a template
12// generator (and which will be cached).
13new 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
18str
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
28return 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>

转载于:https://www.cnblogs.com/zhenxiong/p/3619455.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值