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

Asked

Viewed 877 times

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!

  • 2

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

  • That helped, man, thank you. If you want to write back, feel free. Still I couldn’t understand why my approach didn’t work...

  • How these elements were added to the page after loading it through the method append, they won’t recognize the event click calling in the traditional way $(".excluirUpload").click, therefore, it is necessary to delegate the event click via document, 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 the class specified (excluirUpload) to apply the specified function.

1 answer

3


You need to register the event this way

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

This is because your code runs whenever the page is fully loaded (ready) and after having the elements loaded Javascript adds these listeners to them.

However, you are adding a new element and not adding one Listener to this specific element.

The way I showed above, the event is tied to the HTML document and the second parameter causes it to be triggered only if it is triggered by some element with the specified selector.

See some publications on these subjects that can help you:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.