背景:由于对JavaScript字符串拼接JavaScript变量产生了反感,也想用用JavaScript模板库,看了几个,由于时间原因选择了,因为Visual Studio 对其的语法高亮支持。
0. 下载 jQuery templates plugin
1. 准备工作
1.1 JSON数据
JSON数据在这里类似于“接口文档”,明确哪些数据必须对应到HTML的哪个位置,还有一些作为判断条件的字段,可以根据字段不同的值来显示不同的样式;这里采用一段经转换(JSON.parse(/*JSON String*/))好的数据
1 var MockResponseFromServer = { 2 code: '1', // '1'表示获取数据成功 3 data: [ 4 { 5 productid: "001", 6 productname: "Lumia 930", 7 productnumber: "GD1502001", 8 productpic: "http://www.globalmediahk.com/uploads/magazine/15/3cc3ca3f-a403-42d9-a850-b9d08c88fd48.jpg", 9 memberprice: 35,10 price: 35,11 quantity: 012 },13 {14 productid: "002",15 productname: "Lumia 520",16 productnumber: "GD1502002",17 productpic: "http://blog.orange.pl/uploads/media/b/9/c/5/3/189d1cfd42952ad73b4d91c4700016151d0",18 memberprice: 35,19 price: 35,20 quantity: 021 }],22 msg: '成功'23 };
1.2 HTML
HTML 转换为 x-jquery-tmpl,{ {}} ,${} { {if}}具体语法请参见插件的示例文档,这些符号在Visual Studio 下有语法高亮
1
2. 编写HTML
1 238 9 10 11 12产品列表
4
567
3. JavaScript
1 (function ($) { 2 var IAPP = {}; 3 4 IAPP.ProductTmpl = 'ProductTmpl'; 5 IAPP.$ProductContainer = $('#ProductContainer'); 6 7 function setLazyloadImg() { 8 ///9 /// 设置图片延迟加载10 /// 11 $('img.lazy').lazyload({12 effect: 'fadeIn'13 , failure_limit: 1014 , threshold: 5015 , event: 'scroll'16 });17 }18 19 IAPP.loadDataByAjax = function (handler) {20 ///21 /// AJAX请求产品JSON数据22 /// 23 /// success回调处理函数24 $.ajax({25 type: 'POST',26 url: 'url/getdata.ashx',27 data: { cmd: 'productlist' },28 dataType: 'json',29 success: handler,30 error: function () {31 // error handler32 console && console.info('error:some message');33 // 当AJAX请求发生错误时,用模拟数据测试模板34 handler(MockResponseFromServer);35 }36 });37 };38 39 IAPP.loadDataByAjaxHandler = function (result) {40 ///41 /// 回调函数42 /// 43 /// response from server44 var l = 0, // 用于保存产品的个数45 data, // 产品列表(Array)46 entityObj; // 用于保存产品实体对象47 48 if (!result) { throw 'no response from server'; }49 50 if (result.code && result.code === '1') {51 result.data && (data = result.data);52 if (data && data.length) {53 l = data.length;54 while (l--) {55 entityObj = data.shift();56 // 产品链接57 entityObj['productDetailUrl'] = './product.aspx?pid=' + entityObj.productid;58 59 $.tmpl(IAPP.ProductTmpl, entityObj).appendTo(IAPP.$ProductContainer);60 }61 62 setLazyloadImg(); // 延迟加载63 }64 } else {65 console && console.error(result.msg);66 }67 };68 69 ({70 initTmpl: function () {71 ///72 /// 初始化jQuery.tmpl73 /// 74 75 // $.template(name/*模板名称*/,tmpl/*模板字符串*/)76 // 说明:使用此方式可以根据模板名访问模板以达到复用模板77 $.template(IAPP.ProductTmpl, $('#productItemTmpl').html());78 },79 initData: function () {80 ///81 /// 获取数据82 /// 83 IAPP.loadDataByAjax(IAPP.loadDataByAjaxHandler);84 }, init: function () {85 ///86 /// 所有的初始化动作87 /// 88 this.initTmpl();89 this.initData();90 }91 }).init();92 93 }(jQuery));