jQuery - How to remove row dynamically created table?

0

I'm starting the studies in jQuery and I have the following doubt:

I have a table created in HTML. This table contains only one line with th 's. The records are inserted by jQuery. Through interaction with the user, the data is obtained and saved in variables, then added to the table with append :

$("table").append("<tr><td>" + nome + "</td><td>" + quantidade +
"</td><td>" + valor + "</td><td>" + dataFormatada + "</td><td>" +
acoes + "</td></tr>");

So far, everything works correctly and I can insert all the records.

The actions variable was defined as follows:

var acoes = "<a href='#' class='exclui'>Excluir</a> <a href='#' class='cor'>Mudar Cor</a>";

That is, I would like to be allowed to delete and change the color of each record. For the first part, I already tried hide , remove and the code below, but nothing worked:

$(".exclui").click(function() {
    //$(this).parent().remove();
});

I imagine it to be simple, but I could not. Can someone help me? Thank you.

    
asked by anonymous 04.09.2018 / 20:45

1 answer

2

It is necessary to use EventDelegation , that is, the event handler is in some parent element of the elements that will be inserted in the future. This way when the element is inserted and an event occurs in it, this element propagates to the parents until it reaches the handler.

jQuery already does this with the jQuery.on() method.

Example:

$("#tabela").on('click', '.exclui', function() {
  $(this).closest('tr').remove();
});


// Apenas insere <tr> dinamicamente para demonstração
var $tbody = $('#tabela').find('tbody');
$('#add-tr').on('click', function() {
    $tbody.append('
      <tr>
        <td>Valor 1</td>
        <td>Valor 2</td>
        <td><button class="exclui">X</button></td>
      </tr>
    ');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><buttonid="add-tr">Adiciona linha</button>

<table id="tabela">
  <thead>
    <tr>
      <th>Campo 1</th>
      <th>Campo 2</th>
      <th>Campo 3</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>
    
04.09.2018 / 20:52