jQuery does not recognize .click event of a class added with append [duplicate]

2

Folks, I can not get the .click event of a button that is added with the append command to work.

Here is the function that contains 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 click event of the button:

    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);
            }
        );
    });

Would it be because of .append, this .click event is not recognizing the class of this button ?? How to proceed ??

Another thing I tried was to call a function with onclick, but I need to pass this $ table as a parameter and, when I get in the function as a parameter, if I print, my return is [Object object]. Either approach would be useful, but I could not make either of them work.

Thank you!

    
asked by anonymous 08.11.2017 / 13:54

1 answer

2

You need to sign up for the event this way

$(document).click('.excluirUpload', function(){ ... });

This happens because your code runs whenever the page loads completely ( ready ) and after having the elements loaded, JavaScript adds these listeners to them.

However, you are adding a new element and you are not adding a listener to this particular element.

As I've shown above, the event is bound to the HTML document and the second parameter causes it to only be triggered if it is triggered by some element with the specified selector.

See some publications on these subjects that may help you:

08.11.2017 / 14:00