2010-02-09 6 views
2

Je construted ma table comme suit:ajouter dynamiquement supprimer des lignes de table à l'aide jquery

<table id="dataTable"> 
      <thead> 
       <tr><th>Name</th> 
       <th>Value</th></tr> 
      </thead> 
<TR><TD>Scooby Doo</TD><TD>6</TD><TD><INPUT TYPE="Button" onClick="AddRow()" VALUE="Add Row"></TD></TR> 
</table> 

Lorsque le bouton Ajouter une ligne est cliqué, je dois changer le bouton à un bouton de suppression et insérer une nouvelle ligne sur la première ligne. La première ligne doit contenir le même que dans le code. Comment puis-je faire ceci?

En cliquant sur le bouton Supprimer, Imust peut-il supprimer la ligne à laquelle appartient le bouton Supprimer?

Répondre

1

Quelque chose comme?

$('#dataTable thead').prepend('<tr><th>Name</th><th>Value</th></tr>'); 

Et pour la suppression:

$('#dataTable thead tr').click(function() { 
$(this).hide(); //hide the row, this doesn't delete it. 
}); 

.

8

Hope this helps

$(function(){ 
    $("input[type='button'].AddRow").toggle(
    function(){ 
     var el = $(this); 
     el.closest('tr').clone(true).prependTo(el.closest('table')); 
     el.attr("value", "Delete row"); 
    }, 
    function(){ 
     $(this).closest('tr').remove();   
    }); 
}); 

<table id="dataTable" border="1"> 
    <thead> 
     <tr> 
      <th> 
       Name 
      </th> 
      <th> 
       Value 
      </th> 
     </tr> 
    </thead> 
    <tr> 
     <td> 
      Scooby Doo 
     </td> 
     <td> 
      6 
     </td> 
     <td> 
      <input type="Button" value="Add Row" class="AddRow"> 
     </td> 
    </tr> 
</table> 

Working Demo

Questions connexes