In html there is <div id="tableContainer">and to it I appended dynamically created a table

table = $("<table id="myTable" class='helpTable'>");
table.append("<tr id='1'><td>content<td></tr>");code
table.append("<tr id='2'><td>content<td></tr>"); code
$('#tableContainer').append(table);

Now I want to add event on table row like

 $("#myTable tr").on('click',function(event) {
alert("Hi"); });

Its not working, however following is case is working

$("#tableContainer").on('click',function(event) {
alert("Hi"); });

i.e. I can have event on static html tag

有帮助吗?

解决方案 2

Here is final solution using delegation

$("#tableContainer").on('click', 'tr', function (event) { alert("Hi");});

Its delegation from parent element to child.

Jquery is shorthand for Javascript, delegation for dynamic elements is not looking shorthand.

其他提示

You need to use event delegation as the table and the tr elements are created dynamically

$("#tableContainer").on('click', '#myTable tr', function (event) {
    alert("Hi");
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top