by aherrick
24. June 2010 10:47
Use jQuery objects to build up your table instead of using string concatenation. How many time have you seen code similar to the following to build up a table?
$(function () {
var content = '';
content += '<div id="tableWrap">';
content += '<table id="basicTable">';
for (var i = 0; i < 200; i++) {
content += '<tr>';
content += '<td>';
content += i;
content += '</td>';
content += '<td>';
content += 200 - i;
content += '</td>';
content += '</tr>';
}
content += '</table>';
content += '</div>';
$('body').append(content);
});
Let's use jQuery's built in ability to build up the objects and take a look at how we could write this differently below.
$(function () {
var $wrap = $('<div>').attr('id', 'tableWrap');
var $tbl = $('<table>').attr('id', 'basicTable');
for (var i = 0; i < 200; i++) {
$tbl.append(
$('<tr>')
.append($('<td>').text(i),
$('<td>').text(200 - i))
);
}
$wrap.append($tbl);
$('body').append($wrap);
});
View the live code here!
d159cf6a-1f2f-4674-b4f6-01ffcd02a48f|22|3.5
Tags: