How should I add multiple identical elements to a div with jQuery

前端 未结 4 595
粉色の甜心
粉色の甜心 2020-12-31 09:13

I need to add multiple empty divs to a container element using jQuery.

At the moment I am generating a string containing the empty html using a loop

         


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-31 09:52

    The fastest way to do this is to build the content first with strings. It is MUCH faster to work with strings to build your document fragment before working with the DOM or jquery at all. Unfortunately, IE does a really poor job of concatenating strings, so the best way to do it is to use an array.

    var cont = []; //Initialize an array to build the content
    for (var i = 0;i<10;i++) cont.push('
    bunch of text
    '); $('#container').html(cont.join(''));

    I use this technique a ton in my code. You can build very large html fragments using this method and it is very efficient in all browsers.

提交回复
热议问题