因此下面的代码使用 javascript 动态添加 html 表单元素。 问题是,如果我添加新的 html 表单元素,然后用我想要的内容更新它(即输入 abc),然后单击添加另一个它会删除我之前输入的内容并将其重置为原始文本。
例如:
点击“添加更多数据”
然后我将“名字”更改为 John,将“姓氏”更改为 Doe。
然后我再次单击“添加更多数据”,John 已重置为“First name”,Doe 已重置为“Last name”。
我该如何解决这个问题?
<script>
var x = 1;
function add() {
var fooId = "foo";
for (i=1; i<=3; i++)
{
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", fooId+x+i);
element.setAttribute("name", fooId+x+i);
element.setAttribute("id", fooId+x+i);
if(i==1){
element.setAttribute("value", "First name");
}
if(i==2){
element.setAttribute("value", "Last name");
}
if(i==3){
element.setAttribute("value", "age");
}
var foo = document.getElementById("fooBar");
foo.appendChild(element);
foo.innerHTML += ' ';
}
i++;
var br = document.createElement("br");
foo.appendChild(br);
x++;
}
</SCRIPT>
<body>
<center>
<form id="form" name="form" action="test.php" method="post" enctype="multipart/form-data">
<input type="text" id="foo01" name="foo01" value="first name">
<input type="text" id="foo02" name="foo02" value="last name"/>
<input type="text" id="foo03" name="foo03" value="age">
<br>
<span id="fooBar"></span>
<FORM>
<INPUT type="button" value="Add more data" onclick="add()"/>
<input type="submit" value="Submit">
</center>
</FORM>
</form>
</body>
最佳答案
这行很奇怪:
foo.innerHTML += ' ';
导致问题,删除它时,一切正常。 您可以改用它:
var space = document.createTextNode(" ");
foo.appendChild(space);
关于javascript - 动态添加 html 表单元素和更新的数据被重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18509282/