With jQuery 1.7x, I’m creating whole tables within dynamically generated tabs that have several columns, some of which need to be clickable.
Everything seems to be wonderful except that elusive click event on dynamic content. I just learned how to do this for list items by using the .on method, but it doesn’t seem to work for my tables. (If it matters, each jQuery tab is dynamically added for a given year, and the table on that tab contains all meetings held that year)
What am I missing? I’ve got this at http://jsfiddle.net/KYkRZ/
<table>
<tr><td><span class="ClickableClass">Is Clickable</span></td><td>Regular TD</td></tr>
</table>
<div id='myTab'></div>
$('.ClickableClass').on('click',function() {alert("ClickableClass click event") });
$('#myTab').append('<table border></table>');
var myTable = $('#myTab').children();
for(i=0;i<3;i++){
var mySpan = $('<span></span>').addClass('ClickableClass').text('Should be clickable ' + i);
var myTD = $('<td></td>').append( mySpan );
var myTR = $('<tr></tr>').append( myTD );
$(myTable).append( myTR );
}
Also, I don’t know that this is the best way to construct a table on the fly, but it was the clearest for me to understand, so any suggestions to that end would be appreciated. 🙂
You are adding the event handlers to the objects, then creating new ones and never adding event handlers to the new ones. There are two ways you can deal with this. The first is just to add event handlers after each, but that duplicates code. If you know you’re going to have dynamic content the better approach is to add the event handler to the container and tell the container to look for the click event in an element of a specific type by passing a selector to the event.