2012-10-23 67 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); 
相關問題