簡體   English   中英

如何使用Javascript刪除動態字段

[英]How remove dynamic fields with Javascript

我正在學習具有動態字段的javascript,除了使它們與表匹配之外,我還希望能夠消除它們,以便以后使用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 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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM