Manipulate elements created via jQuery

Asked

Viewed 33 times

1

I created this very simple code to illustrate my doubt:
Here I have an html table with some lines, each row has a trigger that removes it via jQuery.
In the table tfoot there is a driver that inserts via jQuery a new row inside the table, this new one is created containing a driver to remove it.
The problem: The new line removal driver does not work.

$(function() {
	$('span.close').on({
    click: function() {
      $('tr#color-'+$(this).data('ref')).remove();
    }
  });
  $('span.plus').on({
    click: function() {
      var trs = $('table.devcolors tbody tr');
      var ct = trs.length + 1;
      var line = '<tr id=color-'+ct+'> <th>Cor 0'+ct+'</th><td><span class=close data-ref='+ct+'>X</span></td></tr>';
      $('.devcolors tbody').append(line);
    }
  });
})
table {width:100%;}
td {text-align:center;}
.close, .plus {cursor:pointer;}
.close:hover {color:red;}
.plus:hover {color:green;}
th, td {border-bottom:solid 1px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<table class="devcolors">
  <thead>
    <tr>
      <th>Nome</th>
      <th>Remover</th>
    </tr>
  </thead>
  <tbody>
    <tr id="color-1">
      <th>Cor 01</th>
      <td><span class="close" data-ref="1">X</span></td>
    </tr>
    <tr id="color-2">
      <th>Cor 02</th>
      <td><span class="close" data-ref="2">X</span></td>
    </tr>
    <tr id="color-3">
      <th>Cor 03</th>
      <td><span class="close" data-ref="3">X</span></td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <th></th>
      <th>
        <span class="plus">+</span>
      </th>
    </tr>
  </tfoot>
</table>

  • Leigmar, I believe it is for a simple reason: when loading the page, the "on.click" function is linked internally to the nodes, and when it adds new nodes, the function is not assigned to them. Try to extract, just for testing, the function by placing the attribute "onClick" in the HTML calling the function to delete.

  • Utilize $('table').on('click', 'span.close', /* função */). This way, every time the user clicks on the table, the jQuery will automatically check if it was in any span.close. An alternative is to use the property onclick.

  • @Valdeirpsr Thanks, I adapted the syntax to your suggestion and it worked. Thanks anyway!

1 answer

0

For the new elements created dynamically, Event Listener is not being applied, since in this implementation it is only listening to the elements already created (Color 01, Color 02, Color 03).

Replace the $('span.close').on({}) for something like:

$(document).on('click', 'span.close', function(){
    $('tr#color-'+$(this).data('ref')).remove();
});

Browser other questions tagged

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