开发者

Using jQuery to append inside a loop. There must be a better way

I have code (using jQuery) like the following:

var $parent = $('#parentContainer');
$.each([[],[],[],...[]], function(index, innerArray) {
    $.each(innerArray, function(innerIndex, innerValue) {
        $parent.append($('<div />', { ... }));
    });
});

I know this is massively inefficient. I originally tried this with $.map instead of $.each. I would return the DIVs from the inner $.map and each of those arrays would be returned from the outer $.map. Then I would try something like $parent.append(arrayOfArrays). I would then get an uncaught exception some time later. The code with $.each works but I know开发者_运维技巧 there is another way using arrays and appending them all at once. Was I even close with the $.map implementation? Am I missing another way? thanks By the way, i am a total newb at this so I realize I may be doing this totally wrong.


I'm not entirely sure what you're trying to achieve here, but on general principles, injecting directly into the DOM tends to be slow. Injecting into the DOM in a loop is therefore going to be very slow.

A better approach is to build up your collection of elements to insert in the loop, and then append() the entire collection when the loop is finished. This replaced multiple DOM updates with a single one, taking the expensive DOM updating out of the loop.


construct your html and do a appened after the loop

like this eample

noteffective

var arr = reallyLongArray;
$.each(arr, function(count, item) {
    var newTr = '<tr><td name="pieTD">' + item + '</td></tr>';
    $('table').append(newTr);
});

effective

var arr = reallyLongArray;
var textToInsert = '';
$.each(arr, function(count, item) {
    textToInsert  += '<tr><td name="pieTD">' + item + '</td></tr>';
});
$('table').append(textToInsert);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜