Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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("");
 });
share|improve this question
    
Could also use DataTables, a plugin for jQuery. Datatables.net –  user10614 Feb 1 '12 at 14:56

2 Answers 2

up vote 2 down vote accepted

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");
share|improve this answer

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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