开发者

Is there any difference in following 2 jquery code snippet?

开发者 https://www.devze.com 2023-04-07 16:13 出处:网络
Is there any difference in following 2 jquery snippet? Both gives same output but does any one have any advantage over other or they are just one\'s choice to write like this to do the thing.

Is there any difference in following 2 jquery snippet? Both gives same output but does any one have any advantage over other or they are just one's choice to write like this to do the thing.

Snippet 1:

div = $("#myDiv");
div.append("<ul>");
$.each(cobj, function(k,v) {
    div.append("<li><span class='"+v+"'>"+k+"</span></li>");
});
div.append("</ul>");

Snippet 2:

$("<ul>").attr("id", "myUL").appendTo("#myDiv"); 
$.each(cobj, function(k, v) {  
    var li = $("<li>");  
    $("<span>").text(k).attr开发者_开发知识库("class",""+v}).appendTo(li);
    li.appendTo("#myUL");  
});  


Both are not good ways to manupulate the DOM tree in terms of performance. I would suggest the following:

var ul = $("<ul id='myUL'>");
$.each(cobj, function(k,v) {
    ul.append("<li><span class='"+v+"'>"+k+"</span></li>");
});
$("#myDiv").append(ul);

In this way, browser does not re-render page after each li is appended, the entire list is build offline and then appended with single call.


In 1 the UL has no ID, whereas in 2 it has ID="myUL"

0

精彩评论

暂无评论...
验证码 换一张
取 消