Add click event on all buttons with pure Javascript, which is equivalent to jQuery

Asked

Viewed 261 times

0

function Listar(){
   var tbl = document.querySelector("#tblListar");
   tbl.innerHTML = 
    "<thead>"+
    "   <tr>"+
    "   <th>Código</th>"+
    "   <th>Nome</th>"+
    "   <th>Telefone</th>"+
    "   <th>Email</th>"+
    "   </tr>"+
    "</thead>"+
    "<tbody>"+
    "</tbody"
;

var tbody = tbl.querySelector("tbody");

for(var i in tbClientes){
    var cli = JSON.parse(tbClientes[i]);
    tbody.insertAdjacentHTML("beforeend",
                            "<tr>"+
                                 "  <td>"+cli.Codigo+"</td>" + 
                                 "  <td>"+cli.Nome+"</td>" + 
                                 "  <td>"+cli.Telefone+"</td>" + 
                                 "  <td>"+cli.Email+"</td>" + 
                                 "  <td><button data-i='"+[i]+"' class='btnEditar'>Editar</button>"+
                                 "  <button data-i='"+[i]+"' class='btnExcluir'>Excluir</button></td>" + 
                             "</tr>");

 } 

}

  $("#tblListar").on("click", ".btnExcluir", function(){ 
    indice_selecionado = parseInt(this.getAttribute("data-i")); 
        alert(indice_selecionado);
       Listar();
  })

The above code works normally, but I need to do it in pure Javascript. I tried something like this, but the event of click in the buttons:

document.querySelector("#tblListar .btnExcluir").addEventListener("click", function(){
    indice_selecionado = parseInt(this.getAttribute("data-i")); 
    alert(indice_selecionado);
    Listar();
})
<table id="tblListar">
<thead>
 <tr>
   <th>Código</th>
   <th>Nome</th>	
   <th>Telefone</th>
   <th>Email</th>	
 </tr>
</thead> 
<tbody>
  <tr>
   <td>01</td>	
   <td>cjshdvcnac</td>	
   <td>239923929</td>	
   <td>ajcjcsjcjcja</td>	
   <td><button data-i="0" class="btnEditar">Editar</button> 
   <button data-i="0" class="btnExcluir">Excluir</button> 
   </td>
 </tr>
  <tr>
   <td>02</td>	
   <td>Ansc</td>	
   <td>239923929</td>	
   <td>ajcjcsjcjcja</td>	
   <td><button data-i="0" class="btnEditar">Editar</button> 
   <button data-i="0" class="btnExcluir">Excluir</button> 
   </td>
 </tr>

</tbody>
</table>

  • 3

    Regardless of what was suggested in the answer of the question, the codes are not equivalent, this your jQuery code uses "delegation", so the event is not applied directly to the elements with the class .btnExcluir, what it does is a "match" to detect if Event.target in #tblListar obtained in one of the descendants with the same class as .btnExcluir. The difference of setting the event directly to your buttons is that you could delete and add the buttons dynamically always need to add the events again, it’s just an example of use. But to reinforce the answer is not equivalent.

  • @Guilhermenascimento is now equivalent. D

  • @Sam is now "almost", but there are details that differentiate, with the record of events, but I won’t even go into detail, because the problem is more in the question than in the answer, after all it is a case of "Helpdesk".

  • @Guilhermenascimento I think if he hadn’t even tried it would be a case of Helpdesk himself.

1 answer

4


Create a onclick in the body that will click on any element of body whole. Then you check if the clicked element has the class .btnExcluir:

document.body.onclick = function(e){
   if(~Array.from(e.target.classList).indexOf("btnExcluir")){
      var indice_selecionado = parseInt(e.target.dataset.i);
      alert(indice_selecionado);
      Listar();
   }
}

See example:

document.body.onclick = function(e){

   if(~Array.from(e.target.classList).indexOf("btnExcluir")){
      var indice_selecionado = parseInt(e.target.dataset.i);
      alert(indice_selecionado);
      Listar();
   }
   
}

function Listar(){}

// daqui pra baixo não é pra copiar.
// é apenas uma função para criar uma nova linha
// para ilustrar o funcionamento com elementos dinâmicos
document.getElementById("add").onclick = function(){
   
   document.querySelector("#tblListar tbody").innerHTML += '<tr>'
   +'<td>03</td>	'
   +'<td>Ansc</td>'	
   +'<td>239923929</td>	'
   +'<td>ajcjcsjcjcja</td>	'
   +'<td>'
   +'<button data-i="3" class="outraclasse btnExcluir">Excluir</button> '
   +'</td></tr>';
   
}
<table id="tblListar">
<thead>
 <tr>
   <th>Código</th>
   <th>Nome</th>	
   <th>Telefone</th>
   <th>Email</th>	
 </tr>
</thead> 
<tbody>
  <tr>
   <td>01</td>	
   <td>cjshdvcnac</td>	
   <td>239923929</td>	
   <td>ajcjcsjcjcja</td>	
   <td>
   <button data-i="0" class="btnExcluir">Excluir</button> 
   </td>
 </tr>
  <tr>
   <td>02</td>	
   <td>Ansc</td>	
   <td>239923929</td>	
   <td>ajcjcsjcjcja</td>	
   <td>
   <button data-i="1" class="outraclasse btnExcluir">Excluir</button> 
   </td>
 </tr>

</tbody>
</table>
<button id="add">Adicionar nova linha</button>

  • 1

    Sam always present. Rs

  • Sam, I tested your code and the click event only works the first time I click on a button, it shows the Alert and then when I click again does not trigger the event anymore, which may be?

  • @Sam On the same button and on the others too.

  • @Sam tested and made the same mistake.

  • @Sam will put the List() function in the post

  • @Luanrodrigues There really was a problem in the code, but I’ve changed it properly.

Show 1 more comment

Browser other questions tagged

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