jQuery appending an array of elements

后端 未结 9 686
星月不相逢
星月不相逢 2020-12-13 23:34

For the purpose of this question lets say we need to append() 1000 objects to the body element.

You could go about it like this:

         


        
相关标签:
9条回答
  • 2020-12-14 00:15

    You could just call

    $('body').append(elements.join(''));
    

    Or you can just create a large string in the first place.

    var elements = '';
    for(x = 0; x < 1000; x++) {
        elements = elements + '<div>'+x+'</div>';
    }
    $(document.body).append(elements);
    

    Like you mentioned, probably the most "correct" way is the usage of a DocFrag. This could look like

    var elements = document.createDocumentFragment(),
        newDiv;
    for(x = 0; x < 1000; x++) {
        newDiv = document.createElement('div');
        newDiv.textContent = x;
        elements.append( newDiv );
    }
    $(document.body).append(elements);
    

    .textContent is not supported by IE<9 and would need an conditional check to use .innerText or .text instead.

    0 讨论(0)
  • 2020-12-14 00:15

    Upgrade to jQuery 1.8, this works as intended:

    ​$('body')​.append([
        '<b>1</b>',
        '<i>2</i>'   
    ])​;​
    
    0 讨论(0)
  • 2020-12-14 00:17

    You could use an empty jQuery object instead of an array:

    var elements = $();
    for(x = 0; x < 1000; x++) {
        elements = elements.add('<div>'+x+'</div>');
        // or 
        // var element = $('<div>'+x+'</div>');
        // elements = elements.add(element);
    }
    $('body').append(elements);
    

    This might be useful if you want to do stuff with newly generated element inside the loop. But note that this will create a huge internal stack of elements (inside the jQuery object).


    It seems though that your code works perfectly fine with jQuery 1.8.

    0 讨论(0)
提交回复
热议问题