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>
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.– Guilherme Nascimento
@Guilhermenascimento is now equivalent. D
– Sam
@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".
– Guilherme Nascimento
@Guilhermenascimento I think if he hadn’t even tried it would be a case of Helpdesk himself.
– Sam