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\$
1
  • \$\begingroup\$ Could also use DataTables, a plugin for jQuery. Datatables.net \$\endgroup\$
    – user10614
    Commented Feb 1, 2012 at 14:56

2 Answers 2

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\$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.