jq dynamic splicing of html pages and data

Posted by Hellbringer2572 on Wed, 22 Dec 2021 22:25:35 +0100

1, jq dynamic splicing html page

Requirements:
1. The page content is not dead
2. Dynamically load page data according to background data

realization:

Before that, we need to understand the difference between apppend() and html():
Simply put, the append () method is to add an element to the element list, but html () is to replace the data in the element. If you need to page feed, you'd better use the html () method for navigation

For details, please refer to: The difference between append() and html()

Without much nonsense, go straight to the code:

1. First of all, you can add an id or class name to the parent tag where dynamic splicing is required. The difference is not great. Individuals add className as follows (templateArea is where we will splice html pages and data):

<body>
<div class="page">
    <div class="tab_line clearfix">
        <a class="tab_line_a" href="/reportPage?mainId=${mainId !}&year=${year !}&isFillIn=${mainId !}">Medical quality</a>
        <a class="tab_line_a" href="/reportPageOperate?mainId=${mainId !}&year=${year !}&isFillIn=${isFillIn !}">Operational efficiency</a>
        <a class="tab_line_a now_a">sustained development</a>
        <a class="tab_line_a" href="/reportPageSatisface?mainId=${mainId !}&year=${year !}&isFillIn=${isFillIn !}">Satisfaction</a>
    </div>
    <div class="templateArea">

    </div>
    <div class="bottom">
        <a href="/homepage" class="operation_line_button fr">return</a>
        <div class="operation_line_button operation_line_button_blue fr save">preservation</div>
    </div>
</div>
</body>

2.ajax can select the splicing process according to the data situation and needs. The following is my personal needs:
The main steps are:
a. Create a new variable to store the page, that is: var list = ""
b. Put the corresponding page in the list. If you need to put an input, it is: List + = "input tag". This is mainly the format
c. Finally, $(". Templatearea") append(list)

These are probably the three steps, but the requirements are different, so we can make changes according to our own situation with this idea

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 == "qualitative") {
                                    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=\"Please select\" style=\"cursor: auto;\">\n" +
                                            "                                <img alt=\"choice\" 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 == "ration") {
                                    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)
            }
        })
    }

Here is my assembly code. I splice it in three cases. It varies according to needs. This method is a little stupid. However, as a background developer, sometimes I can't think of ideas. This splicing can be regarded as a solution

Finally, let's see the effect:

Here, I first load the header information bb, and then load three different boxes (drop-down box, input box, two conditions and one result box)

2, Tencent template encapsulates data

Here is an extension of other data encapsulation methods template template engine framework. Here is a slight change based on Tencent template

I use template-native-3.0 1. JS if you are interested, you can find the source code and have a look
Personally, I think it's cool for template to be used for loops such as these table s (don't spray big guys)
Use the following:
1. First, js get the background data list and encapsulate it through 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. Then call the method on the page as follows:
Page call is mainly divided into several steps:
a. Set template name = "the name you set in js"
b. Cyclic data (I use the list here because I am paging, and the last layer is the list directory, and then you can cycle according to the data)
c. Just put in the data

3. The effect is as follows:

Finally, let's put down template-native-3.0 1. JS source code is interested in the following:

!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 = {"<": "&#60;", ">": "&#62;", '"': "&#34;", "'": "&#39;", "&": "&#38;"}, 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
}();

3, Summary

When we encapsulate the page and data, the page doesn't move most of the time, and then the data encapsulation is traversed in a loop, but you can't resist the demand. Strange, but it's not very difficult to take it to the page append(), and you can learn three times in a row~

Topics: Javascript JQuery