使用jQuery删除表格行

18

以下是我的代码

脚本

$(document).ready(function(){
    $('#click').click(function(){
        $('#table').append('<tr><td>&nbsp;</td></tr>');
    })
    $('#remove').click(function(){
        $('#table').remove('<tr><td>&nbsp;</td></tr>');
    })
})

HTML

<table width="100%" border="1" cellspacing="0" cellpadding="0" id="table">
    <tr>
        <td>&nbsp;</td>
    </tr>
    <tr>
        <td>&nbsp;</td>
    </tr>
</table>
<div id="click">click</div>
<div id="remove">remove</div>

我成功地添加了一行,但我不知道如何删除表格的最后一行。您可以查看在线演示

我该怎么做?

另外,我希望当用户点击任何一行时,它将删除自己。我已经尝试过,但是有个问题,如果单击行,则会删除自身,但是当您通过在#click中单击添加一行时,单击行时不会自动删除该行。

以下是我的代码:

脚本

$(document).ready(function(){
    $('#click').click(function(){
        $('#table').append('<tr><td>&nbsp;</td></tr>');
    })
    $('#remove').click(function(){
        $('#table tr:last').remove();
    })
    $('#table tr').click(function(){
        $(this).remove();
    });
})

你的脚本不知道要删除哪一行... 绑定 .on() 事件然后尝试。 - sree
我想使用单元格中特定的项目ID将其删除? - Sohaib
6个回答

34
如果您想移除表格#table的最后一行,您需要使用选择器来定位它,然后调用$.remove()方法:
$('#remove').on("click", function(){
    $('#table tr:last').remove();
})

1
为了使动态内容的行号唯一,您可以通过附加类似于以下php代码的唯一标识来实现:<tr id="myTableRow<?php echo $id; ?>">,在删除时也是同样的操作 :) - Sagar Naliyapara

5

您不能这样删除,您需要指定要删除的节点$('#table tr:first'),然后再将其删除remove()

$('#remove').click(function(){
    $('#table tr:first').remove();
})

http://jsfiddle.net/2mZnR/1/


2
一个演示可以在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('<tr><td>foo add&nbsp;</td></tr>');
    })
    $('#remove').click(function(){
        $('#table tr:last').remove();
    })
})

1
你可以在按钮点击时使用表格类从表格中删除最后一个。

$('#remove').on("click", function(){
    $('.tbl tr:last').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="tbl" width="100%" border="1" cellspacing="0" cellpadding="0" >
    <tr>
        <td>&nbsp;</td>
    </tr>
    <tr>
        <td>&nbsp;</td>
    </tr>
</table>
<button id="remove">remove</button>


0
如果您想在单击表格行时删除该行本身,则可以这样做:
$('table tr').on("click", function(){
    $(this).remove();
});

如果您想在表格末尾点击按钮时添加行,请使用以下代码:
 $('#click').click(function(){
    $('#table').append('<tr><td>Xyz</td></tr>');
})

0

使用选择器找到最后一行,然后删除该行,代码如下:

$('#table > tr:last').remove();

这将删除表中的最后一行。如果你想要删除第一行呢?

$('#table > tr:first').remove();

就是这样。有一个关于jQuery的在线编程课程,名为CodeSchool。在那里你会发现很多有价值的内容,包括选择器和DOM操作等。以下是链接:http://jqueryair.com/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接