如何删除表中的行?

时间:2016-11-04 15:14:21

标签: javascript html

我想删除我在函数add()中创建的行。当我使用函数deleteRow()时,行将被删除,但我无法再次使用我的add()函数。有人知道为什么吗?

var trIdP =0;
function add() {
 var typeP = document.getElementById("typeP").value;
 var valueP = document.getElementById("valueP").value;
 var newText = document.createTextNode(typeP);
 var newText2 = document.createTextNode(valueP+" Eur");
 var newText3 = document.createTextNode("button");
 var tablePr = document.getElementById("tableP").getElementsByTagName('tbody')[0];
 if ((typeP != "") && (valueP != "")) {       
     var newRow = tablePr.insertRow(trIdP);
     newRow.id = ("trP"+trIdP);
     var newCell1 = newRow.insertCell(0);
     var newCell2 = newRow.insertCell(1);
     var newCell3 = newRow.insertCell(2);

     newCell1.appendChild(newText);
     newCell2.appendChild(newText2);
     newCell3.innerHTML = "<a onclick=\"deleteRow("+trIdP+")\"><img   src=\"x.gif\" alt=\"Delete row\"></a>";

     document.getElementById("typeP").value = "";
     document.getElementById("valueP").value = "";

     trIdP++;
 }
}

function deleteRow(id){
      document.getElementById("trP"+id).remove();
}

1 个答案:

答案 0 :(得分:1)

您忘记减少trIdP计数器了。

更新

// Use nextAll()
.closest(".basket__item-cell.basket__item-name")
.nextAll(".basket__item-cell.basket__item-qty")
.remove();

// Use nextAll().first() if you there might be more
.closest(".basket__item-cell.basket__item-name")
.nextAll(".basket__item-cell.basket__item-qty")
.first()
.remove();

// use .siblings 
.closest(".basket__item-cell.basket__item-name")
.siblings(".basket__item-cell.basket__item-qty")
.remove();

// Go up to parent, then down
// Most likely to work if the structure changes
.closest(".basket__item-cell.basket__item-name")
.parent()
.find(".basket__item-cell.basket__item-qty")
.remove();

// Go up to parent in one step, then down
// Most likely to work if the structure changes
.closest(".basket__item-data")
.find(".basket__item-cell.basket__item-qty")
.remove();

Check out this plunker