3
\$\begingroup\$

More readable way to do this?

renderHtmlTable(function(tableItems) {

  var tableArray,_i,item,_len;
  tableArray = ['<table id = sampleTable ><thead><tr>' +
                        '<th>Header 1</th>' +
                        '<th>Header 2</th>' +
                        '<th>Header 3</th>' +
                        '<th>Header 4</th>' +
                        '</tr></thead>'];

  for (_i = 0, _len = tableItems.length; _i < _len; _i++) {
    item = tableItems[_i];

    tableArray.push('<tr><td>' + item.foo + '</td>' + 
                      '<td>' + item.bar + '</td>' +
                      '<td>' + item.baz + '</td>' +
                      '<td>' + item.qux + '</td></tr>')
  }          

  tableArray.push('</table>');

 ($('#TableDiv')).html(function() {
   return lessonArray.join("");
 });
\$\endgroup\$
  • \$\begingroup\$ Could also use DataTables, a plugin for jQuery. Datatables.net \$\endgroup\$ – user10614 Feb 1 '12 at 14:56
3
\$\begingroup\$

this seems a little bit more readable (at least to me :)

    var table = $("<table>").attr("id", "sampleTable ")
        .append($("<thead>")
                .append($("<tr>")
                    .append($("<th>").text("Header 1"))
                    .append($("<th>").text("Header 2"))
                    .append($("<th>").text("Header 3"))
                    .append($("<th>").text("Header 4"))
                )
        );

    for (var i = 0; i < 10; i++) {
        table.append($("<tr>")
                .append($("<td>").text("foo"))
                .append($("<td>").text("bar"))
                .append($("<td>").text("foo"))
                .append($("<td>").text("bar"))
        );
    }
    table.appendTo("body");
\$\endgroup\$
4
\$\begingroup\$

Use mustache.js! It's a js templating engine which will point you in the right direction :)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.