jQuery - Best Practice for creating complex HTML Fragments

后端 未结 9 1466
情深已故
情深已故 2021-01-30 03:21

Is there a general best practice for creating somewhat complex HTML elements in jQuery? I\'ve tried a few different ways.

First I tried using createElement and chaining

9条回答
  •  失恋的感觉
    2021-01-30 03:35

    It is more readable and maintainable if the JavaScript code resembles the HTML tag structure. You can go the official jQuery route using $('div', { 'class': 'etc'})...

    Here is a slightly different approach using a function $$ to make each element an editable jQuery object. It should be pretty fast as there is no html parsing taking place.

    $$('div', {'id':'container'},
        $$('div', {'id':'my_div'},
            $$('h1',{'class':'my_header'},
                $$('a',{'href':'/test/', 'class':'my_a_class'}, 'teststring'))));
    

    This makes the approach more flexible and you can add event handlers, data etc. to the nested jQuery objects using chaining quite easily e.g.

    $$('div', {'id':'container'},
        $$('div', {'id':'my_div'},
            $$('h1',{'class':'my_header'},
                $$('a', { 'href': '/test/', 'class': 'my_a_class' }, 'teststring')
            ).click(function() { alert('clicking on the header'); })
        ).data('data for the div')
    ).hide();
    

    The code is more readable than if one were to use the official jQuery approach of doing it with separate calls to .append(), .text(), .html() etc. or by feeding the jQuery $ a concatenated HTML string.

    Reference function $$:

    function $$(tagName, attrTextOrElems) {
        // Get the arguments coming after the params argument
        var children = [];
        for (var _i = 0; _i < (arguments.length - 2) ; _i++) {
            children[_i] = arguments[_i + 2];
        }
    
        // Quick way of creating a javascript element without JQuery parsing a string and creating the element
        var elem = document.createElement(tagName);
        var $elem = $(elem);
    
        // Add any text, nested jQuery elements or attributes
        if (attrTextOrElems) {
            if (typeof attrTextOrElems === "string") { // text
                var text = document.createTextNode(attrTextOrElems);
                elem.appendChild(text);
            }
            else if (attrTextOrElems instanceof jQuery) { // JQuery elem
                $elem.append(attrTextOrElems);
            }
            else // Otherwise an object specifying attributes e.g. { 'class': 'someClass' }
            {
                for (var key in attrTextOrElems) {
                    var val = attrTextOrElems[key];
                    if (val) {
                        elem.setAttribute(key, val);
                    }
                }
            }
        }
    
        // Add any further child elements or text    
        if (children) {
            for (var i = 0; i < children.length; i++) {
                var child = children[i];
                if (typeof child === "string") { // text
                    var text = document.createTextNode(child);
                    elem.appendChild(text);
                } else { // JQuery elem
                    $elem.append(child);
                }
            }
        }
        return $elem;
    }
    

提交回复
热议问题