JSON JQUERY模板實(shí)現(xiàn)說(shuō)明
更新時(shí)間:2010年07月03日 00:07:13 作者:
用JSON從服務(wù)器端返回?cái)?shù)據(jù)已是大家公認(rèn)的標(biāo)準(zhǔn),因?yàn)樗绦【?使用方便.
可是在客戶端再現(xiàn)數(shù)據(jù)也是一個(gè)不小的問(wèn)題,用javascript處理經(jīng)常會(huì)遇到很繁瑣的事.尤其大批量具有相同結(jié)構(gòu)的數(shù)據(jù),例如表格,處理方式不盡如意.如果能有一個(gè)模板控件,就像服務(wù)器端asp.net Gridview或者repeater一樣的東西就好很多.最近看到一個(gè)非常優(yōu)秀的解決方案,讓我在使用方便的同時(shí)不得不為作者的精巧設(shè)計(jì)而作一番感嘆.該解決方案用了區(qū)區(qū)二十幾行代碼,實(shí)現(xiàn)了別人要用幾十甚至上百K的js庫(kù)所做的工作.它就是John Resig 的 Microtemplating engine.大師Rick Strahl有一篇文章專門對(duì)此作了詳細(xì)講述(Client Templating with Jquery).我在這里把最核心部分提取出來(lái)以方便國(guó)人學(xué)習(xí)。
下面一段程序就是microtemplating engine.
var _tmplCache = {}
this.parseTemplate = function(str, data) {
/// <summary>
/// Client side template parser that uses <#= #> and <# code #> expressions.
/// and # # code blocks for template expansion.
/// NOTE: chokes on single quotes in the document in some situations
/// use ’ for literals in text and avoid any single quote
/// attribute delimiters.
/// </summary>
/// <param name="str" type="string">The text of the template to expand</param>
/// <param name="data" type="var">
/// Any data that is to be merged. Pass an object and
/// that object's properties are visible as variables.
/// </param>
/// <returns type="string" />
var err = "";
try {
var func = _tmplCache[str];
if (!func) {
var strFunc =
"var p=[],print=function(){p.push.apply(p,arguments);};" +
"with(obj){p.push('" +
str.replace(/[\r\t\n]/g, " ")
.replace(/'(?=[^#]*#>)/g, "\t")
.split("'").join("\\'")
.split("\t").join("'")
.replace(/<#=(.+?)#>/g, "',$1,'")
.split("<#").join("');")
.split("#>").join("p.push('")
+ "');}return p.join('');";
//alert(strFunc);
func = new Function("obj", strFunc);
_tmplCache[str] = func;
}
return func(data);
} catch (e) { err = e.message; }
return "< # ERROR: " + err.htmlEncode() + " # >";
}
如何使用:
上面程序所用的模板:
如果想用循環(huán):
很簡(jiǎn)單很精巧吧?
下面一段程序就是microtemplating engine.
復(fù)制代碼 代碼如下:
var _tmplCache = {}
this.parseTemplate = function(str, data) {
/// <summary>
/// Client side template parser that uses <#= #> and <# code #> expressions.
/// and # # code blocks for template expansion.
/// NOTE: chokes on single quotes in the document in some situations
/// use ’ for literals in text and avoid any single quote
/// attribute delimiters.
/// </summary>
/// <param name="str" type="string">The text of the template to expand</param>
/// <param name="data" type="var">
/// Any data that is to be merged. Pass an object and
/// that object's properties are visible as variables.
/// </param>
/// <returns type="string" />
var err = "";
try {
var func = _tmplCache[str];
if (!func) {
var strFunc =
"var p=[],print=function(){p.push.apply(p,arguments);};" +
"with(obj){p.push('" +
str.replace(/[\r\t\n]/g, " ")
.replace(/'(?=[^#]*#>)/g, "\t")
.split("'").join("\\'")
.split("\t").join("'")
.replace(/<#=(.+?)#>/g, "',$1,'")
.split("<#").join("');")
.split("#>").join("p.push('")
+ "');}return p.join('');";
//alert(strFunc);
func = new Function("obj", strFunc);
_tmplCache[str] = func;
}
return func(data);
} catch (e) { err = e.message; }
return "< # ERROR: " + err.htmlEncode() + " # >";
}
如何使用:
復(fù)制代碼 代碼如下:
parseTemplate($("#ItemTemplate").html(),{ name: "rick", address: { street: "32 kaiea", city: "paia"} } );
上面程序所用的模板:
復(fù)制代碼 代碼如下:
<script id="ItemTemplate" type="text/html"><div><div><#= name #></div><div><#= address.street #></div> </div></script>
如果想用循環(huán):
復(fù)制代碼 代碼如下:
$.each(dataarray,function(index,dataItem){
parseTemplate($("#ItemTemplate").html(), dataItem );
})
parseTemplate($("#ItemTemplate").html(), dataItem );
})
很簡(jiǎn)單很精巧吧?
相關(guān)文章
jQuery+PHP+Mysql實(shí)現(xiàn)抽獎(jiǎng)程序
這篇文章主要為大家詳細(xì)介紹了jQuery+PHP+Mysql實(shí)現(xiàn)抽獎(jiǎng)程序,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05
JQuery 構(gòu)建客戶/服務(wù)分離的鏈接模型中Table分頁(yè)代碼效率初探
JQuery構(gòu)建客戶/服務(wù)分離的鏈接模型中Table分頁(yè)代碼效率初探!2010-01-01
關(guān)于jquery input textare 事件綁定及用法學(xué)習(xí)
目前1.7以上,jquery的事件綁定已經(jīng)用on替換了原來(lái)的bind,接下來(lái)為大家介紹下bind的使用方法及input textare事件,感興趣的朋友可以參考下哈2013-04-04
使用jQuery UI的tooltip函數(shù)修飾title屬性的氣泡懸浮框
使用jQuery UI的tooltip()函數(shù),可以使懸浮提示框不再那么千篇一律,以下是完整的代碼,感興趣的朋友可以參考下哈,希望對(duì)大家有所幫助2013-06-06
JQuery Study Notes 學(xué)習(xí)筆記(一)
jquery是當(dāng)前比較流行的js類庫(kù),學(xué)習(xí)它可以實(shí)現(xiàn)很多功能。2010-08-08

