【问题标题】:add and remove boxes using javascript使用 javascript 添加和删除框
【发布时间】:2017-04-20 07:55:24
【问题描述】:

我有两个文本框和两个名为添加和删除的按钮。要求是与当前框一起添加更多框。我以某种方式设法添加了盒子,但删除盒子的要求不起作用。请帮助说明为什么此代码不起作用,并在可能的情况下提出可行的解决方案。

function addFunction(){
  var element = document.createElement("input");
  var parent = document.getElementById("form1");
  parent.appendChild(element);
}

function removeFunction(){
  var child = document.getElementsByTagName("input");
  var parent = document.getElementById("form1");

  for (var i = 0; i > child.length; i++) {
    parent.removeChild(child[i]);
  };
}
<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <form id="form1" style="margin-left: 40%; margin-top: 100px;">
      <input type="text" id="one"><br><br><br>
      <input type="text" id="two"><br>
      <p id ="demo"> </p>
    </form>
    <button style="margin-left: 40%;" type="button" value="ADD" id="addButton" onclick="addFunction()">ADD</button>
    <button style="margin-left:50px;" type="button" value="REMOVE" id="removeButton" onclick="removeFunction()">REMOVE</button>
  </body>
</html>

【问题讨论】:

标签: javascript html textbox add removechild


【解决方案1】:
for (var i = 0; i <  child.length; i++) {
        parent.removeChild(child[i]);
    };

你的 for 循环中有错误的条件。您的 i 在开始时始终为 0,并且小于包含节点元素的数组的长度,因此循环无法启动。 附:而且你不需要var i 在它之前

【讨论】:

    【解决方案2】:

    你的 for 循环是错误的:

            for (var i = 0; i > child.length; i++) {
                parent.removeChild(child[i]);
            };
    

    你需要把“>”改成“

    【讨论】:

      【解决方案3】:

      用 条件。您希望执行 for 循环,直到它达到 child.length。

      【讨论】:

      • 是的,我做到了,但它说我的赞成票已被记录,但由于我的声誉少于 15 个,因此不会公开显示..
      猜你喜欢
      • 2014-10-01
      • 2017-12-11
      • 1970-01-01
      • 2021-08-28
      • 2018-04-02
      • 2018-01-31
      • 1970-01-01
      • 1970-01-01
      • 2018-11-13
      相关资源
      最近更新 更多