追加到每个迭代内的dom或创建一个数组和输出?(Appending to the dom inside each iteration or create an array and output?)

编程入门 行业动态 更新时间:2024-10-19 17:18:29
追加到每个迭代内的dom或创建一个数组和输出?(Appending to the dom inside each iteration or create an array and output?)

我昨天发布了一个处理解析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

更多推荐

本文发布于:2023-07-17 13:11:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1144948.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   创建一个   迭代   dom   Appending

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!