gpt4 book ai didi

javascript - 单击按钮时的新输入

转载 作者:行者123 更新时间:2023-11-28 05:18:36 27 4
gpt4 key购买 nike

这个问题真的很菜鸟,但是有人能告诉我这段代码有什么问题吗?

我正在尝试在单击按钮时动态创建新的输入框,旁边有一个新按钮。

我希望新的输入框和按钮具有不同的 ID,以便之后删除它们。

奖励问题:我将如何删除特定的输入框和按钮?

var counter = 1;

function addInput(){
var newdiv = document.createElement('div');
newdiv.id = dynamicInput[counter];
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'> <input type='button' value='-' onClick='removeInput("+dynamicInput[counter]+");'>";
document.getElementById('formulario').appendChild(newdiv);
counter++;
}
<form method="POST" id="formulario">
<div id="dynamicInput[0]">
Entry 1<br><input type="text" name="myInputs[]">
<input type="button" value="+" onClick="addInput();">
</div>
</form>

最佳答案

此外,您还可以删除创建的元素:

<html>
<head>
<script>
var counter = 1;
var dynamicInput = [];

function addInput(){
var newdiv = document.createElement('div');
newdiv.id = dynamicInput[counter];
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'> <input type='button' value='-' onClick='removeInput("+dynamicInput[counter]+");'>";
document.getElementById('formulario').appendChild(newdiv);
counter++;
}

function removeInput(id){
var elem = document.getElementById(id);
return elem.parentNode.removeChild(elem);
}
</script>
</head>
<body>
<form method="POST" id="formulario">
<div id="dynamicInput[0]">
Entry 1<br><input type="text" name="myInputs[]">
<input type="button" value="+" onClick="addInput();">
</div>
</form>
</body>
</html>

关于javascript - 单击按钮时的新输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42015443/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com