2

所以下面的代码使用javascript动态添加html表单元素。问题是,如果我添加新的 html 表单元素,然后用我想要的内容更新它(即输入 abc),然后单击添加另一个它会擦除我之前输入的内容并将其重置为原始文本。

例如:

点击“添加更多数据”

然后我将“名字”更改为 John,将“姓氏”更改为 Doe。

然后我再次单击“添加更多数据”,John 被重置为“名字”,Doe 被重置为“姓氏”。

我该如何解决?

<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>
4

1 回答 1

0

这很奇怪,但这一行:

foo.innerHTML += ' ';

导致问题,删除它时,一切正常。您可以改用它:

var space = document.createTextNode(" ");
foo.appendChild(space);   

看看:http: //jsfiddle.net/Jk8Jm/3/

于 2013-08-29T12:11:22.300 回答