I have a problem when converting a static html table to one which is generated by JavaScript. Previously, my js/jQuery code set click handlers on the data elements in the table as follows:
$(function() {
$('my_table td').click(function(e) {
...handler code
});
This works fine, but I've had to change my table so that the contents are dynamically generated in JavaScript:
// 'table_contents' is "<table><tbody>...</tbody></table>"
$('#my_table').html(table_contents);
When I do this, I lose the click handlers. I suppose this isn't surprising, since I'm just deleting the old html and replacing it with new html. However, I don't know how to handle this properly. Can I just give my anonymous function a name and call it whenever I change the html, or do I have to do something else, like explicitly adding an event listener to each new td
element? And do I have to do anything to clean up after replacing the old html, like freeing the old handler/listener? Does js have memory/resource leaks that I have to fix manually?
Thanks.
EDIT
Sorry to be dumb about this, but I can't get the suggested on/delegate solutions to work. My test html is:
<div id="date_test">
<table><tbody><td>42</td></tbody></table>
</div>
I've tried to respond to a click on td
'42' in 3 different ways:
$("#date_test").on("click", "td", function() {
alert($(this).text());
});
$('#date_test').delegate('td', 'click', function() {
alert($(this).text());
});
$(function() {
$('#date_test td').click(function() {
alert($(this).text());
})
})
Of these, only the third one works. Note that this is completely static code; it's 3 different cut-down test cases. for the first 2 cases, the code is never executed; I can put in a syntax error instead of the alert, and it makes no difference. Any idea what I'm doing wrong? I'm on jQuery 1.7. Thanks.