简体   繁体   中英

Best way to create new DOM elements using Jquery

is it better to create a DOM element like this:-

            var option='';
            var objY = $('select[name="yaxis"]');
            for(var key in summaryObj)
            {
                option += '<option value="'+summaryObj[key]+'">'+key+'</option>';
            }
            objY.html(option);

or like this,

            var objY = $('select[name="yaxis"]');
            var option = document.createElement("option");
            for(var key in summaryObj)
            {
                var san = summaryObj[key];
                objY.append($(option).clone().attr({value:san,text:key}));
            }

For perfomance, this is probably among the fastest ways

var option = document.createElement("option");
var frag   = document.createDocumentFragment();

for (var key in summaryObj) {
    var clone = option.cloneNode();
    clone.value = san;
    clone.innerHTML = key;

    frag.appendChild(clone);
}

$('select[name="yaxis"]').append(frag);

For readability, I like this

var objY = $('select[name="yaxis"]');
var frag = [];

$.each(summaryObj, function(key, val) {
    frag.push(
        $('<option />', {
            value : san,
            text  : key
        })
    );
});

objY.append(frag);

In jQuery, you Do it like this:

var select = $('<select>').attr('name','yaxis');
var option = $("<option>");
option.text('word').value('word');
select.append(option);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM