javascript - 我正在使用 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>
解决方案
如果您的意思是第二次(第三次,第四次)使用按钮添加输入而不是调整那里的总数,那么您的代码中没有任何内容试图避免这种情况。您正在添加输入的数量。
您可以找出有多少并对此进行调整,请参阅评论:
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>
推荐阅读
- javascript - 有没有办法从外部范围调用异步函数?
- javascript - 正则表达式围绕变量定位特定字符
- python - 我的输出低于完整路径,我不希望只输出完整路径,例如“Hello”作为输出
- pyspark - 如何从pyspark列中的文件名中获取文件ID
- apache - 重定向 301 将旧 URL 附加到新 URL
- material-ui - 材料 Ui 导入给出错误“模块构建失败:错误:ENOENT:没有这样的文件或目录”
- c++ - 查找位于数组的最大和最小元素之间的元素的乘积
- ethereum - 在 ethers.js (bsc) 中以编程方式购买一定数量的代币
- html - 可滚动的 flex 列将文档高度推到 100% 以上,导致 2 个滚动条
- powershell - 如何根据我的数据发送电子邮件。.csv 文件