jQuery appending an array of elements

后端 未结 9 718
星月不相逢
星月不相逢 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:17

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

    var elements = $();
    for(x = 0; x < 1000; x++) {
        elements = elements.add('
    '+x+'
    '); // or // var element = $('
    '+x+'
    '); // 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.

提交回复
热议问题