AceTemplate前端模版的递归和关键字组合使用示例
HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>ace-template</title> <style type="text/css"> .keyword{ color:red;} </style> <script type="text/javascript" src="js/jquery-1.9.0.js"></script> <script type="text/javascript" src="js/ace-template.js"></script> <script id="t1" type="text/template"> $.each(this,function(i,data){ <li> <a href="#{data.url}">!#{helper.keyword(data.name)}</a> if(data.items){ <ul> !#{helper.format("t1",data.items)} </ul> } </li> }); </script> </head> <body> <div> <h3>地区</h3> <div>输入关键字:<input id="k1" type="text" value="" /></div> <ul id="t1out"> </ul> </div> </body> </html>
JS:
$(function(){ var citys = [{ name: "北京市", url: "http://baike.baidu.com/view/2431.htm", items: [{ name: "朝阳区", url: "http://baike.baidu.com/view/138836.htm" }, { name: "海淀区", url: "http://baike.baidu.com/view/138838.htm" }] }, { name: "山西省", url: "http://baike.baidu.com/view/6204.htm", items: [{ name: "太原市", url: "http://baike.baidu.com/view/23736.htm", items: [{ name: "迎泽区", url: "http://baike.baidu.com/view/556105.htm", items: [{ name: "大关帝庙", url: "http://baike.baidu.com/view/1947078.htm" }] }, { name: "杏花岭区", url: "http://baike.baidu.com/view/90492.htm" }, { name: "万柏林区", url: "http://baike.baidu.com/view/498669.htm" }] }, { name: "大同市", url: "http://baike.baidu.com/view/28133.htm" }] }]; var query; /** * 高亮关键词 * @param {String} text 字符串原文 * @return {String} 返回标记关键词后的HTML字符串 */ function keyword2(text){ var r = AceTemplate.format("#{this}",text); // 原文做html编码 if(query){ var t = AceTemplate.format("#{this}",query); // 搜索关键字做html编码 r = r.replace(t,AceTemplate.format('<b class="keyword">!#{this}</b>',t)); } return r; } var t1 = document.getElementById("t1out"); var k1 = document.getElementById("k1"); function queryChange(){ if(query === k1.value) return; // 值没改变 query = k1.value; t1.innerHTML = AceTemplate.format("t1",citys,$.extend({},AceTemplate,{keyword:keyword2})); } k1.onkeyup = queryChange; queryChange(); });
- 模板中可以调用自身递归输出。
- 使用html编码输出可以这样:AceTemplate.format("#{this}", text);
-
通过helper参数,加入keyword方法,JS代码61行中使用了jQuery.extend()函数扩展keyword方法;或者用
AceTemplate.keyword = keyword2; t1.innerHTML = AceTemplate.format("t1",citys);