我正在使用 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>


呼啦一阵风
浏览 200回答 1
1回答

回首忆惘然

如果您的意思是第二次(第三次、第四次)使用按钮会添加输入而不是调整那里的总数,那么您的代码中没有任何内容试图避免这种情况。您正在添加输入的数量。您可以找出有多少并对此进行调整,请参阅评论:function numbchild() {&nbsp; var z = document.form2;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// *** Added `var`&nbsp; var ax = parseInt(z.no_child.value);&nbsp; // *** Added `var`, parse it just once here&nbsp; // *** Get the parent element&nbsp; var parent = document.getElementById('xx');&nbsp; // *** Get its existing inputs&nbsp; var inputs = parent.querySelectorAll("div.input");&nbsp; if (inputs.length < ax) {&nbsp; &nbsp; // Need to add some&nbsp; &nbsp; ax -= inputs.length; // Allow for the ones we already have&nbsp; &nbsp; var i;&nbsp; &nbsp; for (i = 0; i < ax; i++) { // *** Don't parse it here&nbsp; &nbsp; &nbsp; // *** Note wrapping the inputs in divs so&nbsp; &nbsp; &nbsp; // its' easy to remove them (and that gives&nbsp; &nbsp; &nbsp; // us the line break as well)&nbsp; &nbsp; &nbsp; parent.insertAdjacentHTML(&nbsp; &nbsp; &nbsp; &nbsp; "beforeend", // *** Add them at the end, not the beginning&nbsp; &nbsp; &nbsp; &nbsp; "<div class=input>Enter student 's name:&nbsp; &nbsp;<input type='text ' name='s_name'></div>"&nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; }&nbsp; } else if (inputs.length > ax) {&nbsp; &nbsp; // Need to remove some&nbsp; &nbsp; ax = inputs.length - ax;&nbsp; &nbsp; while (ax--) {&nbsp; &nbsp; &nbsp; parent.removeChild(inputs[inputs.length-1]);&nbsp; &nbsp; }&nbsp; }}<form name="form2">&nbsp; how many children?: <input type="text" name="no_child" size="20" required><br />&nbsp; <input type="button" name="test" onclick="numbchild()">&nbsp; <p id="xx"></p></form>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript