2012-10-23 86 views
3

以下哪些代码示例在使用jQuery生成HTML代码时速度更快?jquery.clone()和字符串的简单串联之间的区别

样品1:

var div = $("<div>"); 
$.each(data,function(count,item){ 
    var Elem = div.clone().addClass("message").html(item.Firstname); 
    $(".container").append(Elem); 
}); 

样品2:

$.each(data,function(count,item){ 
    var Elem = "<div class = 'Elem'>" + item.Firstname + "</div>"; 
    $(".container").append(Elem); 
}); 
+0

+1问得好。很想看到答案。不幸的是,我现在没时间自己做速度测试。 – Marc

+0

在第一种方法中,为什么不在原始div中包含该类,_before_循环开始? – nnnnnn

+0

为什么问自己什么时候可以测试它? http://jsperf.com/ – epascarello

回答

2

注意,代替或者这些方法,你可以创建一个模板元素直接使用虚拟数据的html,克隆模板,然后用您检索的特定数据替换该数据。更容易调试,因为您可以简单地显示模板元素,以确保它能够完全按照您的要求显示。

换句话说:

<div id='template' style='display:none'> 
    <h1>Name Placeholder</h1> 
    <div class='address'> 
    Street address placeholder 
    </div> 
... lots of complex html here 
</div> 

...的JS是这样的:

var template = $('#template'); // Already created html element with whatever intricacies you like. 
$.each(data,function(count,item){ 
    var Elem = template.clone().addClass("message").html(item.Firstname); 
    // Ok, so don't just replace the inner html, you'll probably want to replace more complex instances in the html with this technique. 
    Elem.show(); // Unhide the element... 
    $(".container").append(Elem); // Then append it. 
}); 
0

样品2将是快速的。追加一个字符串比追加一个jQuery对象快,因为您需要首先从中获取字符串内容。此外,你做了clone,做addClass,做html在样品1。

0

我认为这些都不会给你最好的结果。如果您希望最佳性能缓存数组中的所有字符串并最后添加所有字符串。

var divs = []; 
$.each(data, function(count, item) { 
    divs.push('<div class="message">'+ item.Firstname +'</div>'); 
}); 
$('.container').append(divs.join('')); 

为了获得更好的性能,请使用常规的for循环。

0

我想象样本2会快很多。

如果你正在寻找更多的效益 - 你可以生成元素的列表,然后在一次追加他们都:

var elements = $.map(data,function(count,item){ 
    return "<div class = 'Elem'>" + item.Firstname + "</div>"; 
}); 

$(".container").append(elements); 
相关问题