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

前端 未结 4 560
粉色の甜心
粉色の甜心 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:34

    If you want IE to be fast - or generally consider speed, then you'll want to build up a DOM fragment first before inserting it.

    John Resig explains the technique and includes a performance benchmark:

    http://ejohn.org/blog/dom-documentfragments/

    var i = 10, 
        fragment = document.createDocumentFragment(), 
        div = document.createElement('div');
    
    while (i--) {
        fragment.appendChild(div.cloneNode(true));
    }
    
    $('#container').append(fragment);
    

    I realise it's not making a lot of use of jQuery in building up the fragment, but I've run a few tests and I can't seem to do $(fragment).append() - but I've read John's jQuery 1.3 release is supposed to include changes based on the research linked above.

提交回复
热议问题