在 JavaScript 中使用来自 JSON 的数据动态填充表的快速方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5361810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:52:04  来源:igfitidea点击:

Fast way to dynamically fill table with data from JSON in JavaScript

javascriptjqueryhtmljsondom

提问by Jan Zyka

I am experimenting with jQuery, JSON etc. and came across following task. I have a loader script on the server which returns table data in JSON format. When received the JSON data, I want to fill my table with them. I am currently using code similar to following (there are more columns and some more advanced processing, but you got the idea):

我正在试验 jQuery、JSON 等,并遇到了以下任务。我在服务器上有一个加载程序脚本,它以 JSON 格式返回表数据。收到 JSON 数据后,我想用它们填充我的表。我目前正在使用类似于以下的代码(有更多的列和一些更高级的处理,但你明白了):

...
for (var key=0, size=data.length; key<size;key++) {

  $('<tr>')
            .append( $('<td>').html(
                data[key][0]
            ) )
            .append( $('<td>').addClass('whatever1').html(
                data[key][1]
            ) )
            .append( $('<td>').addClass('whatever2').html(
                data[key][2]
            ) )
            .appendTo('#dataTable');
}
...

<table id="#dataTable"></table>
...

This works pretty much ok. But once the data is growing it's getting terribly slow. For few hunderts of records it take up to about 5s (Firefox, IE) to build the table and that is a bit slow. If I e.g. create the whole HTML on the server and send it as string which I include in the table it will be pretty fast.

这工作得很好。但是一旦数据增长,它就会变得非常缓慢。对于少量记录,构建表最多需要 5 秒(Firefox、IE),这有点慢。例如,如果我在服务器上创建整个 HTML 并将其作为我包含在表中的字符串发送,它将非常快。

So, is there faster way to fill the table?

那么,有没有更快的方法来填表?

NOTE:I know what is paging and I will use it in the end so please don't say "What do you need such a big table on your page for?". This question is about how to fill table quickly no matter how many records you will display :)

注意:我知道什么是分页,我会在最后使用它,所以请不要说“你的页面上需要这么大的表格做什么?”。这个问题是关于无论你将显示多少条记录如何快速填表:)

回答by Neil

See my responseto an earlier similar query using arrays and "join".

请参阅我对使用数组和“连接”的早期类似查询的响应

Don't use jQuery at all until the very end, when you call it just once. Also, cut out string concatenation as well by storing the strings in an array and using the "join" method to build the string in one go.

直到最后才使用 jQuery,当你只调用它一次时。此外,还可以通过将字符串存储在数组中并使用“join”方法一次性构建字符串来删除字符串连接。

e.g.

例如

 var r = new Array(), j = -1;
 for (var key=0, size=data.length; key<size; key++){
     r[++j] ='<tr><td>';
     r[++j] = data[key][0];
     r[++j] = '</td><td class="whatever1">';
     r[++j] = data[key][1];
     r[++j] = '</td><td class="whatever2">';
     r[++j] = data[key][2];
     r[++j] = '</td></tr>';
 }
 $('#dataTable').html(r.join('')); 

回答by Alnitak

Try deferring the addition of the table to the running DOM until as late as possible.

尽量推迟将表添加到正在运行的 DOM 中。

var table = $('<table>');   // create a new table

// populate the rows
....  .append(table);

// replace the existing table all in one go
$('#dataTable').replaceWith(table);

This should prevent any page layout until the whole table is ready.

这应该可以防止任何页面布局,直到整个表格准备就绪。

If performance is a real problem I'd also avoid calling methods that require parsing strings, like all those $('<td>')calls. For a single element the overhead of that is probably quite expensive (although it's worth it if you have a long string of HTML).

如果性能是一个真正的问题,我也会避免调用需要解析字符串的方法,就像所有这些$('<td>')调用一样。对于单个元素,其开销可能非常昂贵(尽管如果您有很长的 HTML 字符串,这是值得的)。

As I understand it, adding large strings of tags using .append()or .html()is supposed to be pretty efficient. What you lose is the control that you would have if you had used .text()to fill the table cells to avoid HTML code injection.

据我了解,使用.append()或添加大字符串标签.html()应该非常有效。如果您曾经.text()填充表格单元格以避免 HTML 代码注入,您将失去控制权。

回答by tvanfosson

It's probably faster to build the HTML for the entire row and add the row to the table rather than adding each individual element one at a time. You could also extend that to building all of the HTML in a string, then adding it all at one go, which would be even faster. In an MVC environment, I'd probably return a partial view (HTML) that has the table since that would maintain separation of concerns. I would avoid building HTML on the server (in a controller), though, as that would mean that you'd have to change code whenever you wanted to change how the table was displayed. If you're using PHP or another scripting language, then filter as appropriate for your environment.

为整行构建 HTML 并将该行添加到表中可能比一次添加一个单独的元素更快。您还可以将其扩展为在一个字符串中构建所有 HTML,然后一次性添加所有内容,这样会更快。在 MVC 环境中,我可能会返回一个包含表的部分视图 (HTML),因为这将保持关注点分离。不过,我会避免在服务器上(在控制器中)构建 HTML,因为这意味着每当您想更改表格的显示方式时都必须更改代码。如果您使用 PHP 或其他脚本语言,请根据您的环境进行过滤。

var html = '';
for (var key=0, size=data.length; key<size;key++) {

  html += '<tr><td>'
             + data[key][0]
             + '</td><td class="whatever1">'
             + data[key][1]
             + '</td><td class="whatever2">'
             + data[key][2]
             + '</td></tr>';
}

$('#dataTable').append(html);