45-问题
5.11.1 问题
你打算加载一个具有1000个姓名和地址的JSON数据对象,并用jQuery以这些数据创建一个表格。在IE 7中创建这个表格花费5~10秒,这还不包括下载时间。
JSON数据格式如下:
{
"names": [
{
"first": "Azzie",
"last": "Zalenski",
"street": "9554 Niemann Crest",
"city": "Quinteros Divide",
"state": "VA",
"zip": "48786"
},
//重复1000个姓名
]
}
JavaScript代码如下:
//返回净化过的文本版本,对& < >等文本进行转义
function esc( text ) {
return text
.replace( '&', '&;' )
.replace( '<', '<;' )
.replace( '>', '>;' );
}
$(document).ready( function() {
function fillTable( names ) {
$.each( names, function() {
$('<tr>')
.append( $('<td>').addClass('name').html(
esc(this.first) + ' ' + esc(this.last)
) )
.append( $('<td>').addClass('address').html(
esc(this.street) + '<br />' +
esc(this.city) + ', ' +
esc(this.state) + ' ' + esc(this.zip)
) )
.appendTo('#nameTable');
});
}
$.getJSON( 'names/names-1000.json', function( json ) {
fillTable( json.names );
});
});
在文档中还有下列HTML代码:
<table id="nameTable">
</table>
这些代码工作得很好,浏览器的显示如图5-1所示。

但是它运行得太慢了。