javascript 删除表中的最后一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10686888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
delete last row in table
提问by Bato Dor
I've got a simple question, I want to delete the last row in a table, I copied one function that deletes the checked one though:
我有一个简单的问题,我想删除表中的最后一行,但我复制了一个删除选中的函数的函数:
function deleterow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=1; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(row);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
How do I change it, so that it will delete only the last row each time it's called? Thank you all for the help! I really appreciate it!
如何更改它,以便每次调用时只删除最后一行?谢谢大家的帮助!对此,我真的非常感激!
回答by jbabey
the deleteRowfunction takes an index, pass it count - 1
.
的deleteRow函数采用的指标,通过它count - 1
。
http://jsfiddle.net/jbabey/HEDNZ/
http://jsfiddle.net/jbabey/HEDNZ/
function deleterow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
table.deleteRow(rowCount -1);
}
回答by Satya
function deleterow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.rows[rowCount - 1 ];
table.deleteRow(row);
}
回答by t c
Why not just use:
为什么不使用:
function deleterow(tableID) {
var table = document.getElementById(tableID);
table.deleteRow(-1);
}
回答by Simon
I haven't tested this but I think something like this should work:
我还没有测试过这个,但我认为这样的事情应该有效:
function deleterow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var lastRow = table.rows[rowCount];
table.deleteRow(lastRow);
}catch(e) {
alert(e);
}
}
回答by Michael Christensen
I wasn't sure if rowCount has some special meaning for you.
我不确定 rowCount 对您是否有特殊意义。
iterating with while-- lets you start from the back first. Just break when you actually remove one.
使用 while 进行迭代——让您先从后面开始。当你真正移除一个时,就打破它。
function deleterow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var i = rowCount;
while(i--) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(row);
rowCount--;
break;
}
}
}catch(e) {
alert(e);
}
}
回答by Diego Estrada
Use table.deleteRow(i);
使用 table.deleteRow(i);
instead
反而
table.deleteRow(row); hope this works :)
table.deleteRow(row); 希望这有效:)