使用JQuery从表中删除行。请参阅代码

时间:2013-09-12 06:47:27

标签: javascript jquery

我使用了网络中的代码,每次onclick事件都会添加一个表格行。它对我来说很完美,直到我意识到我需要为每一行点击一次onclick事件,它会删除该行。

使用我的代码有没有办法实现?

请参阅以下代码:

Javascript / JQuery代码:

<script>
    var counter = 2;            
    function addRow() {
        event.preventDefault();
        var newRow = jQuery('<tr><td><label>'+ counter +'</label></td><td><textarea name="txtActionStep' + counter + '" style="width:300px; height: 50px; word-wrap:break-word;"></textarea></td><td valign="top"><input type="text" name="txtOwner' +              counter + '"/></td></tr>');
        counter++;                
        jQuery('table.actionsteps-list').append( newRow );
    }
</script>

HTML代码:

<table class="actionsteps-list" width="510">
   <tr>
       <th colspan="3" align="left">Action Steps</th>
   </tr>
   <tr>
       <td>Step #</td><td>Action Step</td><td>Owner</td>
   </tr>
   <tr>
       <td><label>1</label></td>
       <td><textarea name="txtActionStep1" style="width:300px; height: 50px; word-wrap:break-word;"></textarea></td>
       <td valign="top"><input type="text" name="txtOwner1" /></td>
   </tr>
</table>
<table width="510">
   <tr>
       <td align="right"><a href="#" title="" onclick="javascript:addRow();">Add Action</a></td>
   </tr>
</table>

谢谢!

2 个答案:

答案 0 :(得分:3)

当然,使用委托我们可以做到这一点。

$('table.actionsteps-list').on('click', 'tr', function(e){
  $(this).remove();
});

你可能想在你的行中添加一个按钮来表示删除,所以让我们假设你添加(到每一行):

<td><button class="delete">Delete</button></td>

然后只需改变你的委托方法:

$('table.actionsteps-list').on('click', '.delete', function(e){ 
  e.preventDefault(); // stops the page jumping to the top
  $(this).closest('tr').remove();
});

答案 1 :(得分:1)

使用委托在表级别捕获事件,这样您添加的任何新行也将被处理:

$('.actionsteps-list').on('click', 'tr', function(){
  $(this).remove();
});

旁注:

不要将javascript:协议用于内联Javascript,仅在将Javascript放入链接的href属性时使用:

<a href="#" title="" onclick="addRow();">Add Action</a>