2
Guys, I’m not getting to make the event . click a button that is added with the append command work.
Here is the function that contains the append:
function mostrarUploads(nome, tabela) {
var $table = $(tabela);
$table.html("");
//apenas atualiza as categorias caso esteja abrindo o collapse, nunca quando está fechando
showPleaseWait();
$.ajax({
url: "/painel/mostrarUploadsCategorias",
method: 'POST',
data: {_token: jQuery(".token").val(), nome: nome},
success: function(e) {
e.forEach(function(item, indice) {
//remove o diretório da string e só deixa o nome final do arquivo
var nomeArquivo = item.replace('public/painel/categorias/' + nome + "/", "");
$table.append("<tr><td>" + nomeArquivo + "</td> <td><a class='btn btn-success' href=\"/painel/fazerDownload/" + nome + "/" + nomeArquivo + "\">Download</a> <button type='button' class='btn btn-danger excluirUpload' data-diretorio=\"" + item + "\">Excluir</button></td></tr>");
});
}
}).done(function() { //só abre o modal assim que terminar a requisição ajax
hidePleaseWait();
});
}
And the button click event:
jQuery(function() {
... algumas outras funções...
$(".excluirUpload").click(
function() {
alert('excluindo');
//carregar os uploads desta categoria
var diretorio = $(this).data('diretorio');
var $table = $(this).closest('.categoria').find("tbody");
excluirUpload(diretorio, $table);
}
);
});
It would be because of . append, this . click event is not recognizing the class of that button?? How to proceed??
Another thing I tried was to call a function with onclick, but I need to pass this $table as parameter and, when arriving at the function as parameter, if I print, my return is [Object Object]. Either of the two approximations would be helpful, but I couldn’t make either one work.
Thank you!
use
$(document).on('click', '.excluirUpload', function(){})
– Rafael Augusto
That helped, man, thank you. If you want to write back, feel free. Still I couldn’t understand why my approach didn’t work...
– Gabriel Augusto
How these elements were added to the page after loading it through the method
append
, they won’t recognize the eventclick
calling in the traditional way$(".excluirUpload").click
, therefore, it is necessary to delegate the eventclick
viadocument
, as the colleague mentioned above, because then it will search in the whole HTML document (the whole page), including elements added after the loading of the same, the elements that have theclass
specified (excluirUpload) to apply the specified function.– Leandro