私は、同じキーを持つが値が異なるオブジェクトでいっぱいの配列を持っています。これらのオブジェクトは、さまざまなサブ要素を持つdivに変換する必要があります。次のコードは機能しますが、扱いにくく、維持管理が難しいようです。配列からのデータに基づいてdom要素を作成するきれいな方法は?
pim.buildProducts = function(array) {
// for each item in the array
productHTML = '';
compareBoxHTML = '<div class="checkbox compare">' +
'<label data-placement="right" data-toggle="tooltip" title="Add to Compare"><span class="compare-text">Compare</span><input type="checkbox" value="compare"></label>' +
'</div>';
for(i = 0; i < array.length; i++) {
// build image
image = '<div class="image"><a href="' + array[i].url + '"><img src="' + array[i].image + '" /></a></div>';
// build description
desc = '<div class="desc"><h4><a href="' + array[i].image + '">' + array[i].id + '</a></h4>' +
'<h5>' + array[i].description + '</h5>';
// build icons
icons = '<div class="pim-icons"><a class="cart" href="' + array[i].url + '"><span class="glyphicon glyphicon-shopping-cart"></span></a>';
if(array[i].catalog) {
icons += '<a class="file" href="' + array[i].catalog + '"><span class="glyphicon glyphicon-file"></span></a>';
}
icons += '</div>';
productHTML += '<div class="product">' + image + desc + icons + '</div>';
}
return productHTML;
};
私が追求できるよりよい方法がありますか?
ありがとうございます! ウォルター
Javascript関数を使用してDOM要素を構築すると「クリーン」に見えるかもしれませんが、必ずしもパフォーマンスにとって最良の方法ではありません。ブラウザは高度に最適化されたHTMLパーサを持っていますが、JSからの増分DOMアップデートはかなり遅くなります。 – Barmar
'createElement'を使うつもりなら、最初にノードを' docfrag'に追加してからDOMにfragを追加してください。 – Andy
@Barmarだから、私はもともとこの方法を使いました。何百もの要素を扱う場合、それらを1つずつ作成するのではなく、一度にすべて出力するほうがパフォーマンスが良いように思えました。 – Walter