一、jq动态拼接html页面
需求:
1.页面内容不是死的
2.根据后台数据动态加载页面数据
实现:
在这之前我们需要了解下apppend()与html()这两个方法的区别:
简单来说就是append()方法是在元素列表添加某个元素,但是html()是替换元素中的数据。如果需要做换页,导航此类的效果最好使用html()方法
详情可参考:append()与html()区别
废话不多说直接上代码:
1.首先 在需要动态拼接的地方的父级标签可以加上一个id或者class类名 区别倒是不大 个人都是加className 如下(templateArea即是 我们会在其下面拼接html页面及数据):
<body> <div class="page"> <div class="tab_line clearfix"> <a class="tab_line_a" href="/reportPage?mainId=${mainId !}&year=${year !}&isFillIn=${mainId !}">医疗质量</a> <a class="tab_line_a" href="/reportPageOperate?mainId=${mainId !}&year=${year !}&isFillIn=${isFillIn !}">运营效率</a> <a class="tab_line_a now_a">持续发展</a> <a class="tab_line_a" href="/reportPageSatisface?mainId=${mainId !}&year=${year !}&isFillIn=${isFillIn !}">满意度</a> </div> <div class="templateArea"> </div> <div class="bottom"> <a href="/homepage" class="operation_line_button fr">返回</a> <div class="operation_line_button operation_line_button_blue fr save">保存</div> </div> </div> </body>
2.ajax获取到数据 根据数据情况和需求可自主选择拼接流程 以下为我个人需求拼接:
主要步骤为:
a.新建变量用来存放页面 即:var list=""
b.将对应页面放到list中 如需要放一个input 则为:list+=“input标签” 主要就是这种格式
c.最后就是$(".templateArea").append(list)
大概就是这三步 但是需求都是不一样的 所以说根据自己情况进行改动 有这个思路就可
function getTemplateList(param) { jQuery.ajax({ url: systemBaseInterface + "/sustainedAdd/findSustainedTemplateList", type: "POST", cache: false, async: false, data: param, dataType: "json", success: function (data, text) { var list = ""; for (var i = 0; i < data.data.length; i++) { if (i == 0) { list += "<div class=\"content\">\n" + " <div class=\"title\">" + data.data[i].content + "<span style=\"float: right\">" + ${year !} + "</span></div>\n" + " <table class=\"content_table\">\n" + " <tr>\n" + " <th></th>\n" + " <th></th>\n" + " <th></th>\n" + " <th></th>\n" + " </tr>" } else { list += "<div class=\"content\">\n" + " <div class=\"title\">" + data.data[i].content + "\n" + " </div>\n" + "<table class=\"content_table functionalPositionArea\">\n" + " <tr>\n" + " <th></th>\n" + " <th></th>\n" + " <th></th>\n" + " <th></th>\n" + " </tr>" } jQuery.ajax({ url: systemBaseInterface + "/sustainedAdd/findSustainedTemplateList", type: "POST", cache: false, async: false, data: {"parentCode": data.data[i].code}, dataType: "json", success: function (data, text) { for (var j = 0; j < data.data.length; j++) { var content = JSON.parse(htmlDecode(data.data[j].content)) if (content.threeType == "定性") { list += " <tr>\n" + " <td class=\"content_table_label\">" + content.threeName + "</td>\n" + " <td colspan=\"3\">\n" + " <div class=\"content_table_block content_table_block1\">\n" + " <div class=\"dropdown\">\n" + " <input name=\"\" autocomplete=\"off\" type=\"text\" data-name=" + content.threeName + " data-code=" + data.data[j].code + " id="+ data.data[j].code +" data-count=" + data.data[j].isCount + " code=" + data.data[j].code + " class=\"dropdown_input normal result\" readonly=\"readonly\" placeholder=\"请选择\" style=\"cursor: auto;\">\n" + " <img alt=\"选择\" src=\"../img/dropdown.png\" class=\"dropdown_img\">\n" + " <ul class=\"dropdown_menu\">" for (var k = 0; k < content.option.length; k++) { list += " <li class=\"overflow dropdown_menu_li\" code=" + k + 1 + ">" + content.option[k].xuanxiang + "</li>\n" } list += " </ul>\n" + " </div>\n" + " </div>\n" + " </td>\n" + " </tr>" } else if (content.threeType == "定量") { for (var k = 0; k < content.tiaojian.length; k++) { if (k == 0) { var kk = k + 1; list += " <tr>\n" + " <td class=\"content_table_label\" rowspan=" + content.tiaojian.length + ">" + content.threeName + "</td>\n" + " <td rowspan=" + content.tiaojian.length + ">\n" + " <div class=\"content_table_block\">\n" + " <input type=\"text\" class=\"content_table_block_text result result_type3\" data-count=" + data.data[j].isCount + " data-code=" + data.data[j].code + " data-name=" + content.threeName + " code=" + data.data[j].code + " id=\"value" + data.data[j].code + "_result\">\n" + " <span class=\"unit overflow\">" + content.threeUnit + "</span>\n" + " </div>\n" + " </td>\n" + " <td class=\"content_table_label\">" + content.tiaojian[0].condition + "</td>\n" + " <td>\n" + " <div class=\"content_table_block\">\n" + " <input type=\"text\" class=\"content_table_block_text condition " + data.data[j].code + "_condition\" data-name=" + content.threeName + " data-count=" + data.data[j].isCount + " data-code=" + data.data[j].code + " code=" + data.data[j].code +"_"+kk +" οnkeyup='keyUp(data.data[j].code,JSON.stringify(content.suanfa))' id=" + data.data[j].code +"_"+kk +">\n" + " <span class=\"unit overflow\">" + content.tiaojian[0].conditionUnit + "</span>\n" + " </div>\n" + " </td>\n" + " </tr>" } else { var kk = k + 1; list += "<tr>\n" + " <td class=\"content_table_label\">" + content.tiaojian[k].condition + "</td>\n" + " <td>\n" + " <div class=\"content_table_block\">\n" + " <input type=\"text\" class=\"content_table_block_text condition " + data.data[j].code + "_condition\" data-name=" + content.threeName + " οnkeyup='keyUp(" + data.data[j].code + "," + JSON.stringify(content.suanfa) + ")' data-code=" + data.data[j].code + " data-count=" + data.data[j].isCount + " code=" + data.data[j].code +"_"+kk +" id=" + data.data[j].code +"_"+kk +">\n" + " <span class=\"unit overflow\">" + content.tiaojian[k].conditionUnit + "</span>\n" + " </div>\n" + " </td>\n" + " </tr>" } } } else { list += "<tr>\n" + " <td class=\"content_table_label\">" + content.threeName + "</td>\n" + " <td colspan=\"3\">\n" + " <div class=\"content_table_block\">\n" + " <input type=\"text\" class=\"content_table_block_text result\" data-name=" + content.threeName + " data-count=" + data.data[j].isCount + " data-code=" + data.data[j].code + " code=" + data.data[j].code + " id="+ data.data[j].code +">\n" + " <span class=\"unit overflow\">" + content.threeUnit + "</span>\n" + " </div>\n" + " </td>\n" + " </tr>" } } list += "</table>\n" + " </div>" } }) } $(".templateArea").append(list) } }) }
这里是我的拼装代码 我是分三种情况进行拼接的 因需求而异 这种方法笨是笨了点 不过身为后台开发的 有时候想不到思路的话这种拼接倒也不失为一种解决方案
最后给大家看下效果:
我这里是先加载头信息 bb 然后加载的是三种不同的框(下拉框 输入框 两条件一结果框)
二、腾讯template封装数据
这里给大家扩展一个其他的封装数据的方法 template模板引擎框架 这里是在腾讯template基础上使用 些许改变
我用的是template-native-3.0.1.js 大家有兴趣可以找下源码看下
个人认为template用于这些table之类的循环是挺爽的(大佬勿喷)
使用如下:
1.首先 js获取到后台数据列表 通过template进行封装
user.userData = function (param) { return $.ajax({ url: systemBaseInterface + "/base/userData", data: param, failed: function (code, msg) { DiaLogBox.error(msg); }, success: function (data) { template.loadData("user", data.data, function (ele) { $(ele).show(); user.tableInit(); }); $("#userlist").setPager(data.data, function () { user.userData(param); }); } }); };
2.然后在页面调用方法如下:
页面调用主要分为几步:
a.设置template-name="你在js中设置的名字"
b.循环数据(我这里的list是因为我是分页 最后一层是list目录 然后你们可以看数据情况进行循环)
c.放入数据即可
3.效果如下:
最后给大家放下template-native-3.0.1.js源码 有兴趣看下:
!function () { function a(a) { return a.replace(t, "").replace(u, ",").replace(v, "").replace(w, "").replace(x, "").split(/^$|,+/) } function b(a) { return "'" + a.replace(/('|\\)/g, "\\$1").replace(/\r/g, "\\r").replace(/\n/g, "\\n") + "'" } function c(c, d) { function e(a) { return m += a.split(/\n/).length - 1, k && (a = a.replace(/\s+/g, " ").replace(/<!--.*?-->/g, "")), a && (a = s[1] + b(a) + s[2] + "\n"), a } function f(b) { var c = m; if (j ? b = j(b, d) : g && (b = b.replace(/\n/g, function () { return m++, "$line=" + m + ";" })), 0 === b.indexOf("=")) { var e = l && !/^=[=#]/.test(b); if (b = b.replace(/^=[=#]?|[\s;]*$/g, ""), e) { var f = b.replace(/\s*\([^\)]+\)/, ""); n[f] || /^(include|print)$/.test(f) || (b = "$escape(" + b + ")") } else b = "$string(" + b + ")"; b = s[1] + b + s[2] } return g && (b = "$line=" + c + ";" + b), r(a(b), function (a) { if (a && !p[a]) { var b; b = "print" === a ? u : "include" === a ? v : n[a] ? "$utils." + a : o[a] ? "$helpers." + a : "$data." + a, w += a + "=" + b + ",", p[a] = !0 } }), b + "\n" } var g = d.debug, h = d.openTag, i = d.closeTag, j = d.parser, k = d.compress, l = d.escape, m = 1, p = {$data: 1, $filename: 1, $utils: 1, $helpers: 1, $out: 1, $line: 1}, q = "".trim, s = q ? ["$out='';", "$out+=", ";", "$out"] : ["$out=[];", "$out.push(", ");", "$out.join('')"], t = q ? "$out+=text;return $out;" : "$out.push(text);", u = "function(){var text=''.concat.apply('',arguments);" + t + "}", v = "function(filename,data){data=data||$data;var text=$utils.$include(filename,data,$filename);" + t + "}", w = "'use strict';var $utils=this,$helpers=$utils.$helpers," + (g ? "$line=0," : ""), x = s[0], y = "return new String(" + s[3] + ");"; r(c.split(h), function (a) { a = a.split(i); var b = a[0], c = a[1]; 1 === a.length ? x += e(b) : (x += f(b), c && (x += e(c))) }); var z = w + x + y; g && (z = "try{" + z + "}catch(e){throw {filename:$filename,name:'Render Error',message:e.message,line:$line,source:" + b(c) + ".split(/\\n/)[$line-1].replace(/^\\s+/,'')};}"); try { var A = new Function("$data", "$filename", z); return A.prototype = n, A } catch (B) { throw B.temp = "function anonymous($data,$filename) {" + z + "}", B } } var d = function (a, b) { return "string" == typeof b ? q(b, {filename: a}) : g(a, b) }; d.version = "3.0.0", d.config = function (a, b) { e[a] = b }; var e = d.defaults = {openTag: "<%", closeTag: "%>", escape: !0, cache: !0, compress: !1, parser: null}, f = d.cache = {}; d.render = function (a, b) { return q(a, b) }; var g = d.renderFile = function (a, b) { var c = d.get(a) || p({filename: a, name: "Render Error", message: "Template not found"}); return b ? c(b) : c }; d.get = function (a) { var b; if (f[a]) b = f[a]; else if ("object" == typeof document) { var c = document.getElementById(a); if (c) { var d = (c.value || c.innerHTML).replace(/^\s*|\s*$/g, ""); b = q(d, {filename: a}) } } return b }; var h = function (a, b) { return "string" != typeof a && (b = typeof a, "number" === b ? a += "" : a = "function" === b ? h(a.call(a)) : ""), a }, i = {"<": "<", ">": ">", '"': """, "'": "'", "&": "&"}, j = function (a) { return i[a] }, k = function (a) { return h(a).replace(/&(?![\w#]+;)|[<>"']/g, j) }, l = Array.isArray || function (a) { return "[object Array]" === {}.toString.call(a) }, m = function (a, b) { var c, d; if (l(a)) for (c = 0, d = a.length; d > c; c++) b.call(a, a[c], c, a); else for (c in a) b.call(a, a[c], c) }, n = d.utils = {$helpers: {}, $include: g, $string: h, $escape: k, $each: m}; d.helper = function (a, b) { o[a] = b }; var o = d.helpers = n.$helpers; d.onerror = function (a) { var b = "Template Error\n\n"; for (var c in a) b += "<" + c + ">\n" + a[c] + "\n\n"; "object" == typeof console && console.error(b) }; var p = function (a) { return d.onerror(a), function () { return "{Template Error}" } }, q = d.compile = function (a, b) { function d(c) { try { return new i(c, h) + "" } catch (d) { return b.debug ? p(d)() : (b.debug = !0, q(a, b)(c)) } } b = b || {}; for (var g in e) void 0 === b[g] && (b[g] = e[g]); var h = b.filename; try { var i = c(a, b) } catch (j) { return j.filename = h || "anonymous", j.name = "Syntax Error", p(j) } return d.prototype = i.prototype, d.toString = function () { return i.toString() }, h && b.cache && (f[h] = d), d }, r = n.$each, s = "break,case,catch,continue,debugger,default,delete,do,else,false,finally,for,function,if,in,instanceof,new,null,return,switch,this,throw,true,try,typeof,var,void,while,with,abstract,boolean,byte,char,class,const,double,enum,export,extends,final,float,goto,implements,import,int,interface,long,native,package,private,protected,public,short,static,super,synchronized,throws,transient,volatile,arguments,let,yield,undefined", t = /\/\*[\w\W]*?\*\/|\/\/[^\n]*\n|\/\/[^\n]*$|"(?:[^"\\]|\\[\w\W])*"|'(?:[^'\\]|\\[\w\W])*'|\s*\.\s*[$\w\.]+/g, u = /[^\w$]+/g, v = new RegExp(["\\b" + s.replace(/,/g, "\\b|\\b") + "\\b"].join("|"), "g"), w = /^\d[^,]*|,\d[^,]*/g, x = /^,+|,+$/g; "function" == typeof define ? define(function () { return d }) : "undefined" != typeof exports ? module.exports = d : this.template = d }();
三、总结
我们页面封装页面及数据的时候大部分时间其实还是页面不用动 然后数据封装用循环遍历 但是你顶不住需求怪呀 但是拼接的话也不是很难 就拿过来页面append()下就可以了 学到三连哈~