Handle event with JQuery when form and link are generated automatically

1

JQuery does not work when the form or a link is generated automatically. Example below:

This example works.

<a id='btnTreatInvite' class='btn btn-primary btn-sm fa fa-check' href='#'>&nbsp; Aceitar</a>  

$("#btnTreatInvite").on("click", function(e){
    e.preventDefault(); 
    alert('event works');       
}); 

When the same link is automatically generated, it does not work.

var table ='<table id="tableInviteRqd">';
    table +='<thead>';
    table +='<tr>';
    table +='<th data-toggle="true">Nome</th>';
    table +='<th data-hide="phone,tablet"></th>';
    table +='</tr>';
    table +='</thead>';
    table +='<tbody>';

$.each(data, function(i, item){ 
    table +='<td>' + item.name + '</td>';
    table += "<td><a id='btnTreatInvite' class='btn btn-primary btn-sm fa fa-check' href='teste.php'>&nbsp; Aceitar</a></td>";
 });                        
    table +='</tbody>';
    table +='</table>'; 
    
asked by anonymous 14.01.2015 / 03:09

1 answer

1

The problem is that you are associating the event with elements that do not exist in the DOM when it is read by the browser.

To resolve, you should make use of delegation , attaching the event to an element that exists on the page at the time it loads and delegates the same to a particular element:

$("body").on("click", ".classeDosLinks", function(e){
    e.preventDefault(); 
    alert('event works');
}); 

At the top is the event attached to body and delegated to elements with the% cs class as%, although you should use a shorter scope , that is, append the event to a more element next to classeDosLinks , maybe a body serving wrapper to dynamic content.

    
14.01.2015 / 10:54