随时添加克隆或创建DOM-哪个更好? [英] Append clone or create DOM on the fly - What is better?
问题描述
我希望从ajax调用返回的数组中列出以下列表.
I wish to make the following list from an array returned from an ajax call.
<ul id="list">
<li><input type="checkbox" name="rss" value="231" />bla</li>
<li><input type="checkbox" name="rss" value="321" checked="checked" />ble</li>
<li><input type="checkbox" name="rss" value="431" />abc</li>
</ul>
以下两种方法都可以使用(我可能需要进行调整,但它们很接近.一种方法优于另一种方法吗?总有更好的方法吗?谢谢
Both of the following will work (I might need to tweak but they are close. Is one method preferred over the other? Is there something better altogether? Thanks
var l=$("#list");
l.html('');
$(data).each(function(){
l.append('<li><input type="checkbox" name="rss" checked="'+((this.selected)?'checked':null)+'" value="'+this.id+'" />'+this.channel+'</li>');
//Or
l.append($("#rss-clone").clone(true).removeAttr('id').find('input').val(this.id).attr('checked',(this.selected)?'checked':null).parent().text(this.channel));
},'json');
//仅适用于克隆解决方案:
//required for clone solution only:
<ul class="hidden"><li id="rss-clone"><input type="checkbox" name="rss" value="" />bla</li></ul>
推荐答案
另请参见:收获是,动态地动态创建Dom会增加客户端的开销,而在客户端上克隆现有Dom的速度很快,但具有必须预先渲染和下载它们的开销.
The takeaway is that dynamically creating doms on the fly adds overhead on the client, whereas cloning existing doms is fast on the client but has the overhead of having to render and download them in advance.
没有一个比另一个更好,哪个更适合您取决于您的项目;如果您更关心客户端性能,而不是每个请求要下载一些额外的字节,那么最好选择克隆方法.
None is the better than the other, which one is more suitable for you depends on your project; if you care more about client performance than a few extra bytes to be downloaded per request you would do good choosing the cloning method for instance.
但是,据我所知,客户端性能不受任何方法的严重影响,克隆的速度如此之快,但动态创建元素的速度却丝毫不差.除非您要创建100个这样的选项,否则选择可能只是取决于口味,即对您而言感觉更好.
As far as I can tell however, the client performance is not severely affected by any of the methods, cloning is ever so slightly faster but dynamically creating elements is not horribly slow by any means. Unless you are creating 100s of these the choice may just come down to a matter of taste, ie what feels better for you.
但是要注意的一件事是,除非您需要创建许多非常不同的元素,否则克隆是一种更为方便的方法,因为如果标记未嵌入到您的JS代码中,则以后可以轻松地对元素进行样式设置和修改.
One thing to note however is that unless you need to create many very different elements, cloning is a more convenient method in that you can easily style and modify the elements afterwards if the markup is not embedded in your JS code.
这篇关于随时添加克隆或创建DOM-哪个更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!