Jquery - 追加与追加

2022-01-22 00:00:00 append jquery javascript appendto

谁能解释一下为什么常规的 Append into a loop 比 AppendTo 效果更好?

Can somebody explain me why regular Append into a loop works better than AppendTo?

//Using Regular Append
var ul = $("<ul></ul>");
$("#myDiv").empty().append(ul)

$.each(movies, function (count, item) {
    var id = 'li_' + count;
    ul.append('<li id=' + id + '>' + item + '</li>');

    $('#' + id).click(function () { });
});

//Using AppendTo
var div = $("#myDiv").empty(),
    ul = $("<ul></ul>").appendTo(div);

$.each(movies, function (count, item) {
    $('<li>' + item + '</li>').click(function () { }).appendTo(ul);
});

结果http://jsperf.com/sdp-jquery-append/3

推荐答案

append(content) 将内容追加到每个匹配元素的内部.

append(content) appends content to the inside of every matched element.

appendTo(selector) 将所有匹配的元素附加到另一组指定的元素.

appendTo(selector) appends all of the matched elements to another specified set of elements.

相关文章