html – jQuery build table with events – Education Career Blog

I’ve just start playing about with jQuery and want to place the results of a ajax call into a table … I’ve written the following function (for test not actual)

 function AjaxSucceeded(result) {
           $("#pageLabel").html('');
           $("#pageLabel").append($("<table>").attr("id", "outputTable").append($('<tbody>')));

           $.each(result.d, function(i, item) {
               $("#outputTable").find('tbody')
                    .append($('<tr>')
                    .attr('onclick', "clientSideInclude('pageLabel','http://wwww.microsoft.com');")
           .append($('<td>')
           .attr('colspan', "2")
           .text(item.Description)
           )
           );

           });
           //** Clean up before we leave
           $('#loadDiv').removeClass('Loading').addClass('notLoading');
       };

Which produces the following output

<tbody><tr onclick="clientSideInclude('pageLabel','http://wwww.microsoft.com')"><td colspan="2">Test Page                                                                                           </td></tr><tr onclick="clientSideInclude('pageLabel','http://wwww.microsoft.com')"><td colspan="2">Test Page 2                                                                                         </td></tr></tbody>

All looks good to me … but the onclick even doesn’t fire …. any ideas as how to fix this ? Thanks

,

try this:

function AjaxSucceeded(result) {

  $("#pageLabel").empty();

  var table = $('<table id="outputTable"><tbody></tbody></table>'),
      reftBody = $(table).find('tbody');

  $.each(result.d, function(i, item) {

      var 
          // td
          td = $('<td>')
                 .attr('colspan', "2")
                 .text(item.Description),
          // tr
          tr = $('<tr>')
                 .bind('click', {pageLabel: 'pageLabel', link: 'http://wwww.microsoft.com'}, function(event) {

                    clientSideInclude(event.data.pageLabel, event.data.link);

                 })
                 .append(td);     
      // append tr
      $(reftBody).append(tr);

   });

   // append table with tbody
   $("#pageLabel").append(table);

   //** Clean up before we leave
   $('#loadDiv').removeClass('Loading').addClass('notLoading');
};

,

Try this:

.append($('<tr onclick="...">')

It’s also much more efficient to build up your HTML as a string and insert the whole thing at once. It greatly reduces the number of redraws the browser needs to execute.

Leave a Comment