首页 > 解决方案 > 我正在使用 for 循环从表单输入打印输出,但输入表单不断添加自身

问题描述

所以我得到了一个关于表格中孩子数量的输入。如果有 2 个子项,则单击按钮后应弹出两个表单,如果是 4,则为 4。但是我的 for 循环不起作用,由于某种原因,表单的值会不断增加,无论我单击多少次按钮,当它应该在超过限制时停止时,它会无限地继续添加。

function numbchild() {
  z = document.form2;
  ax = z.no_child.value;
  var i;
  for (i = 0; i < parseInt(ax); i++) {
    console.log(ax);
    document.getElementById('xx').insertAdjacentHTML(
      "afterbegin",
      "Enter student 's name:   <input type='text ' name='s_name'><br />"
    );
  }
}
<form name="form2">
  how many children?: <input type="text" name="no_child" size="20" required><br />
  <input type="button" name="test" onclick="numbchild()">
  <p id="xx"></p>
</form>

标签: javascripthtml

解决方案


如果您的意思是第二次(第三次,第四次)使用按钮添加输入而不是调整那里的总数,那么您的代码中没有任何内容试图避免这种情况。您正在添加输入的数量。

您可以找出有多少并对此进行调整,请参阅评论:

function numbchild() {
  var z = document.form2;               // *** Added `var`
  var ax = parseInt(z.no_child.value);  // *** Added `var`, parse it just once here
  // *** Get the parent element
  var parent = document.getElementById('xx');
  // *** Get its existing inputs
  var inputs = parent.querySelectorAll("div.input");
  if (inputs.length < ax) {
    // Need to add some
    ax -= inputs.length; // Allow for the ones we already have
    var i;
    for (i = 0; i < ax; i++) { // *** Don't parse it here
      // *** Note wrapping the inputs in divs so
      // its' easy to remove them (and that gives
      // us the line break as well)
      parent.insertAdjacentHTML(
        "beforeend", // *** Add them at the end, not the beginning
        "<div class=input>Enter student 's name:   <input type='text ' name='s_name'></div>"
      );
    }
  } else if (inputs.length > ax) {
    // Need to remove some
    ax = inputs.length - ax;
    while (ax--) {
      parent.removeChild(inputs[inputs.length-1]);
    }
  }
}
<form name="form2">
  how many children?: <input type="text" name="no_child" size="20" required><br />
  <input type="button" name="test" onclick="numbchild()">
  <p id="xx"></p>
</form>


推荐阅读