使用jQuery删除表行
以下是我的代码
脚本
$(document).ready(function(){ $('#click').click(function(){ $('#table').append(' '); }) $('#remove').click(function(){ $('#table').remove(' '); }) })
HTML
click remove
当我添加一行它很好,但我不知道如何删除表的最后一行。 您还可以查看在线演示 。
我怎样才能做到这一点?
另外,我想当用户也点击任何一行时它会自行删除。 我试过了,但是有一个问题。 如果单击该行,它将自行删除,但是当您通过单击#click添加行时,该行不会通过单击来删除自身。
这是我的代码:
脚本
$(document).ready(function(){ $('#click').click(function(){ $('#table').append(' '); }) $('#remove').click(function(){ $('#table tr:last').remove(); }) $('#table tr').click(function(){ $(this).remove(); }); })
如果要删除#table
的最后一行表,则需要使用选择器对其进行定位,然后对其调用$.remove()
:
$('#remove').on("click", function(){ $('#table tr:last').remove(); })
您无法删除,您必须指定要删除哪个节点$('#table tr:first')
并删除它remove()
$('#remove').click(function(){ $('#table tr:first').remove(); })
一个演示在http://jsfiddle.net/BfKSa/, 或者如果你绑定,添加和删除每一行,这个不同的演示 http://jsfiddle.net/xuM4N/派上用场。
API:remove => http://api.jquery.com/remove/
正如您所说:这将删除“删除表格的最后一行”
$('#table tr:last').remove();
会为你的案子做点诀窍。
码
$(document).ready(function(){ $('#click').click(function(){ $('#table').append('foo add '); }) $('#remove').click(function(){ $('#table tr:last').remove(); }) })
使用选择器查找最后一行并删除该行:
$('#table > tr:last').remove();
这将删除表格中的最后一行。 如果要删除第一个怎么办?
$('#table > tr:first').remove();
而已。 有jQuery的codechool在线课程。 你会发现许多有价值的东西,包括选择器和DOM操作。 这是一个链接: http : //jqueryair.com/
您可以使用按钮单击时的表类删除表中的最后一个tr
。
$('#remove').on("click", function(){ $('.tbl tr:last').remove(); });
如果要在单击表行时删除行本身
$('table tr').on("click", function(){ $(this).remove(); });
如果要在表格末尾单击单击按钮时添加行
$('#click').click(function(){ $('#table').append('Xyz '); })