• 使用jquery动态拼接html页面及数据


    一、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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    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 += "
    \n" + "
    " + data.data[i].content + "" + ${year !} + "
    \n"
    + " \n"+" \n"+" \n"+" \n"+" \n"+" \n"+" "}else{ list +="
    \n" + "
    " + data.data[i].content + "\n" + "
    \n"
    + "
    \n"+" \n"+" \n"+" \n"+" \n"+" \n"+" "} 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 +=" \n"+" \n"+" \n"+" "}elseif(content.threeType =="定量"){for(var k =0; k < content.tiaojian.length; k++){if(k ==0){var kk = k +1; list +=" \n"+" \n"+" \n"+" \n"+" \n"+" "}else{var kk = k +1; list +="\n"+" \n"+" \n"+" "}}}else{ list +="\n"+" \n"+" \n"+" "}} list +="
    " + content.threeName + " \n" + "
    \n" + "
    \n" + " + 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" + " \"选择\"\n" + "
      " for (var k = 0; k < content.option.length; k++) { list += "
    • + k + 1 + ">" + content.option[k].xuanxiang + "
    • \n"
      } list += "
    \n"
    + "
    \n"
    + "
    \n"
    + "
    + content.tiaojian.length + ">" + content.threeName + " + content.tiaojian.length + ">\n" + "
    \n" + " + 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" + " " + content.threeUnit + "\n" + "
    \n"
    + "
    " + content.tiaojian[0].condition + " \n" + "
    \n" + " + 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" + " " + content.tiaojian[0].conditionUnit + "\n" + "
    \n"
    + "
    " + content.tiaojian[k].condition + " \n" + "
    \n" + " + 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" + " " + content.tiaojian[k].conditionUnit + "\n" + "
    \n"
    + "
    " + content.threeName + " \n" + "
    \n" + " + 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" + " " + content.threeUnit + "\n" + "
    \n"
    + "
    \n"
    + "
    "
    } }) } $(".templateArea").append(list) } }) }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114

    这里是我的拼装代码 我是分三种情况进行拼接的 因需求而异 这种方法笨是笨了点 不过身为后台开发的 有时候想不到思路的话这种拼接倒也不失为一种解决方案

    最后给大家看下效果:
    在这里插入图片描述

    我这里是先加载头信息 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);
                    });
                }
            });
        };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    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
    }();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137

    三、总结

    我们页面封装页面及数据的时候大部分时间其实还是页面不用动 然后数据封装用循环遍历 但是你顶不住需求怪呀 但是拼接的话也不是很难 就拿过来页面append()下就可以了 学到三连哈~

  • 相关阅读:
    SQLite 知识整理
    代码随想录算法训练营第五十五天| LeetCode392. 判断子序列、LeetCode115. 不同的子序列
    mmdetection ValueError: need at least one array to concatenate解决方案
    实习打怪之路:webpack概念【入口、输出、装载机、插件、模块】(引自官网)
    oscp raven2靶机渗透过程
    基础 | NIO - [Files & Path & Charset]
    springboot+新冠疫苗预约管理系统 毕业设计-附源码241530
    Fast RCNN
    软件TFN 2K的分布式拒绝攻击(DDos)实战详解
    数据结构与算法笔记:基础篇 - 数组:为什么数组都是从0开始编号
  • 原文地址:https://blog.csdn.net/weixin_BJ050106/article/details/126331323