我有这个JS代码,用于在用户单击按钮时添加和删除表行。添加行就像梦一样。我的问题是用户单击“删除”按钮,除了第一行之外的所有行都被删除。我只希望删除最后一行,比如它们是否添加到多行。
修改 我试过这个
function deleteRow(tableID) {
var table = document.getElementById(tableID);
if(table.rows.length <= 1) { // limit the user from removing all the fields
alert("Cannot Remove all the fields.");
break;
}
table.deleteRow(table.rows.length -1);
}
但是当我取出循环时,“添加”按钮不再有效......
<script>
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if(rowCount < 50){ // limit the user from creating fields more than your limits
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i <colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
}else{
alert("Maximum Unit limit is 5");
}
}
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
if(rowCount <= 1) { // limit the user from removing all the fields
alert("Cannot Remove all the fields.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
</script>
答案 0 :(得分:0)
要删除表格的最后一行,您可以使用此功能。
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
table.deleteRow(rowCount -1);
}
答案 1 :(得分:-1)
你不需要for循环,这段代码可以工作:
function deleteRow(tableID) {
var table = document.getElementById(tableID);
if(table.rows.length <= 1) { // limit the user from removing all the fields
alert("Cannot Remove all the fields.");
break;
}
table.deleteRow(table.rows.length -1);
}