javascript - Binding event to dynamically created element -
in 1 of jsp pages project, create append elements table dynamically, way:
$('.auth').each(function(index, elem) { $(elem).click(function(){ //do stuff here! var index = $(elem).data('key'); //this read data-key attribute var div = "#edit_autorizacao_"+index; $(div).toggle(); $('#auth-'+index+' tbody.auth').remove(); var newrow = $('<tr>'); $.ajax({ type: "get", url: "<c:out value="${pagecontext.request.contextpath}/usuario/lista_autorizacao"/>", cache: false }).done(function(data){ var obj_auth = jquery.parsejson( data ); for(var item in obj_auth.auth) { var checkbox = $('<tr>'); checkbox.append('<td><input type="checkbox" class="auth_check" data-user="'+index+'" data-key="'+obj_auth.auth[item].id+'" name="'+obj_auth.auth[item].nome+'"></td> <td>'+obj_auth.auth[item].nome+'</td>'); checkbox.appendto(newrow); } $('#auth-'+index).append('<tbody class="auth">'); $('#auth-'+index+' tbody.auth').append(newrow); }); $.ajax({ type: "get", url: "<c:out value="${pagecontext.request.contextpath}/usuario/lista_autorizacao_usuario"/>", cache: false, data: {id: index} }).done(function(data){ var obj_auth = jquery.parsejson( data ); for(var item in obj_auth.auth) { var checkbox = $('input[name='+obj_auth.auth[item].nome+']'); $(checkbox).attr("checked","true"); } }); }); });
now, each 1 of elements:
checkbox.append('<td><input type="checkbox" class="auth_check" data-user="'+index+'" data-key="'+obj_auth.auth[item].id+'" name="'+obj_auth.auth[item].nome+'"></td> <td>'+obj_auth.auth[item].nome+'</td>');
i want bind 'click' event. right now, doing in way:
$('.auth').on('click', '.auth_check', function(event){ var id_auth = $(this).data('key'); var id_user = $(this).data('user'); $.ajax({ type: "get", url: "<c:out value="${pagecontext.request.contextpath}/usuario/toggle_autorizacao"/>", cache: false, data: {id_usuario: id_user, id_autorizacao: id_auth} }).done(function(data){ if(data == "yes") { $("#result_auth").empty().append("ok").hide(3000); } else if(data == "not") { $("#result_auth").empty().append("erro").hide(3000); } else { $("#result_auth").empty().append("sem acesso").hide(3000); } }); });
but nothing happens when click in element. can point me doing wrong here?
ok, after open topic, find solution problem. happens making binding 2 dynamically created elements; first 1 must static. so, add 'class' atribute 'auth_container' tbody element, , make bind way:
$('.auth_container').on('click', '.auth_check', function(event){
and it's working fine.
Comments
Post a Comment