使用jquery在表中动态添加删除行

use*_*431 2 javascript 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>
Run Code Online (Sandbox Code Playgroud)

单击"添加行"按钮时,我需要将按钮更改为删除按钮并在第一行插入新行.第一行必须包含与代码中相同的内容.我怎样才能做到这一点?

单击删除按钮,Imust能够删除删除按钮所属的行吗?

rah*_*hul 8

希望这可以帮助

$(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>
Run Code Online (Sandbox Code Playgroud)

工作演示