1 回答
TA贡献1847条经验 获得超11个赞
如果您的意思是第二次(第三次、第四次)使用按钮会添加输入而不是调整那里的总数,那么您的代码中没有任何内容试图避免这种情况。您正在添加输入的数量。
您可以找出有多少并对此进行调整,请参阅评论:
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>
添加回答
举报