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();
    });
})
4

6 回答 6

33

如果要删除 的最后一个表行#table,则需要使用选择器定位它,然后调用$.remove()它:

$('#remove').on("click", function(){
    $('#table tr:last').remove();
})
于 2012-05-19T05:54:36.863 回答
5

您不能像那样删除,您必须指定要删除的节点$('#table tr:first')并将其删除 remove()

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

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

于 2012-05-19T05:54:50.777 回答
2

A demo is at http://jsfiddle.net/BfKSa/ or in case you are binding, add and delete to every row, this different demo http://jsfiddle.net/xuM4N/ come in handy.

API: remove => http://api.jquery.com/remove/

As you mentioned: This will delete the "delete the last row of the table"

$('#table tr:last').remove(); will do the trick for your case.

Code

$(document).ready(function(){
    $('#click').click(function(){
        $('#table').append('<tr><td>foo add&nbsp;</td></tr>');
    })
    $('#remove').click(function(){
        $('#table tr:last').remove();
    })
})
于 2012-05-19T06:03:51.337 回答
1

tr您可以在单击按钮时使用表格类从表格中删除最后一个。

$('#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>

于 2016-07-13T08:14:04.730 回答
0

使用选择器找到最后一行,然后像这样删除该行:

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

这将删除表中的最后一行。如果要删除第一个怎么办?

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

而已。有 jQuery 的 codeschool 在线课程。你会在那里找到很多有价值的东西,包括选择器和 DOM 操作。这是一个链接:http: //jqueryair.com/

于 2012-05-19T05:57:11.730 回答
0

如果您想在单击表格行时删除行本身,那么

$('table tr').on("click", function(){
    $(this).remove();
});

如果要在表格末尾单击单击按钮添加行

 $('#click').click(function(){
    $('#table').append('<tr><td>Xyz</td></tr>');
})
于 2016-07-13T10:06:24.990 回答