我昨天发布了一个处理解析json数据的问题。 在其中一个后续答案中,有人说我在每次迭代中使用jQuery append()函数,同时使用each(),从而使性能受到了影响。
我在做:
$.getJSON("http://myurl.com/json?callback=?", function(data) { // loop through each post $.each(data.posts, function(i,posts){ ... parsing ... // append $('ul').append('<li>...</li>'); }); });我修改它是这样的:
$.getJSON("http://myurl.com/json?callback=?", function(data) { // create array arrPosts = new Array(); // loop through each post $.each(data.posts, function(i,posts){ ... parsing ... arrPosts[i] = '<li> ... </li>'; }); // output for (i=0;i<arrPosts.length;i++){ $('ul').append(arrPosts[i]); } });这似乎工作正常,示例演示: http : //jsbin.com/isuro
但我做对了吗? 我有点小菜,只是想确保我正确地接近这一点。 感谢您的任何建议!
I posted a question yesterday dealing with parsing json data. In one of the follow up answers someone said I was taking a performance hit by using the jQuery append() function within each iteration, while using each().
I was doing:
$.getJSON("http://myurl.com/json?callback=?", function(data) { // loop through each post $.each(data.posts, function(i,posts){ ... parsing ... // append $('ul').append('<li>...</li>'); }); });I modified it to be this:
$.getJSON("http://myurl.com/json?callback=?", function(data) { // create array arrPosts = new Array(); // loop through each post $.each(data.posts, function(i,posts){ ... parsing ... arrPosts[i] = '<li> ... </li>'; }); // output for (i=0;i<arrPosts.length;i++){ $('ul').append(arrPosts[i]); } });And this seems to be working properly, example demo: http://jsbin.com/isuro
But am I doing this right? I'm somewhat of a noob and just want to make sure I'm approaching this correctly. Thanks for any advice!
最满意答案
你不应该迭代输出。
$('ul').append( arrPosts.join( "\n" ) );否则看起来不错
you shouldn't have to iterate to output.
$('ul').append( arrPosts.join( "\n" ) );Otherwise looks fine
更多推荐
发布评论