Pergunta

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

Foi útil?

Solução 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.

Outras dicas

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");
});
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top