我使用了从网上获得的代码,它在每个 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>
谢谢!
最佳答案
当然,使用委托(delegate)我们可以做到这一点。
$('table.actionsteps-list').on('click', 'tr', function(e){
$(this).remove();
});
您可能想在行中添加一个按钮以指示删除,因此假设您添加(到每一行):
<td><button class="delete">Delete</button></td>
然后像这样改变你的委托(delegate)方法:
$('table.actionsteps-list').on('click', '.delete', function(e){
e.preventDefault(); // stops the page jumping to the top
$(this).closest('tr').remove();
});
关于javascript - 使用 JQuery 从表中删除行。请看代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18757240/