项目中返回的json数据有深层次的数据要输出
如:
data = [{ status : "success", data : { name : "xiaomi", info : { msg : "成功", code : "100" } } }, { status : "error", data : { name : "xiaoH", info : { msg : "失败", code : "200" } } }, { status : "success", data : { name : "大米", info : { msg : "成功", code : "100" } } } ];
模板:
<tr><td>{{status}}</td><td>{{data.name}}</td><td>{{data.info.msg}}</td></tr>
组合成:
代码:
function tmpl2html(str, arrs) { var REG = /{{[0-9a-zA-Z_.]+}}/g, html = ''; for (var j = 0, arrsLen = arrs.length; j < arrsLen; j++) { html += str.replace(REG, function (key) { key = key.substr(2, key.length - 4); var keyArrs = key.split("."), len = keyArrs.length, tempObj = arrs[j]; for (var i = 0; i < len; i++) { tempObj = tempObj[keyArrs[i]]; } return typeof tempObj == "string" ? tempObj : ""; }); } return html; }