如何使用 Javascript 删除动态字段

How remove dynamic fields with Javascript

我正在学习 javascript 动态字段,除了使它们与 table 匹配之外,我还希望能够消除它们,以便稍后使用 css 我只需要使用 javascript

javascript代码:

function create(){
    var div = document.getElementById("fields");
    var array=document.getElementsByName('txt[]');
    var length = array.length+1;

    var jump = document.createElement("P");

    var input = document.createElement("input");
    input.setAttribute("name", "txt[]");
    input.setAttribute("id", "txtCamp" + length);
    input.setAttribute("size", "20");
    input.className = "input";

    var input2 = document.createElement("input");
    input2.setAttribute("name", "txt2[]");
    input2.setAttribute("id", "txtCamp2" + length);
    input2.setAttribute("size", "20");
    input2.className = "input";

    var button = document.createElement('button');
    button.setAttribute("type", "button");
    button.setAttribute("id", "txtCampo3"+ length);
    button.innerHTML = 'Add field';
    button.setAttribute("onclick", "create()");

    var button2 = document.createElement('button');
    button2.setAttribute("type", "button");
    button2.setAttribute("id", "txtCampo3"+ length);
    button2.innerHTML = 'delete field';

    jump.appendChild(input);
    jump.appendChild(input2);
    jump.appendChild(button);
    jump.appendChild(button2);
    div.appendChild(jump);
}

以及 html

中的 table
<table width="50%"  border="0" cellspacing="5" cellpadding="7">
  <tr>
  <td>
    <input type="button" id="boton" value="Create field" onclick="create();" />
  </td>
  </tr>
  <tr>
    <th>Item1</th>
    <th>Item2</th>
  </tr>
  <tr>      <td>
      <div id="fields"></div>
    </td>
  </tr>
</table>

您可以通过首先获取该特定元素来编写一个函数,然后您可以将其删除,例如

function removeElt(elementId) {
   var element = document.getElementById(elementId);
   element.parentNode.removeChild(element);
}