Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 动态添加html表单元素和更新的数据会被重置_Javascript - Fatal编程技术网

Javascript 动态添加html表单元素和更新的数据会被重置

Javascript 动态添加html表单元素和更新的数据会被重置,javascript,Javascript,下面的代码使用javascript动态添加html表单元素。 问题是,如果我添加新的html表单元素,然后用我想要的内容更新它(即,在abc中键入),然后单击“添加另一个”,它会擦除我以前键入的内容,并将其重置为原始文本 例如: 单击“添加更多数据” 然后我把“名字”改为约翰,“姓”改为多伊 然后我再次点击“添加更多数据”,John被重置为“名字”,Doe被重置为“姓氏” 我该如何解决这个问题 <script> var x = 1; function add() { var foo

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

例如:

单击“添加更多数据”

然后我把“名字”改为约翰,“姓”改为多伊

然后我再次点击“添加更多数据”,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>

var x=1;
函数add(){
var fooId=“foo”;

对于(i=1;i这很奇怪,但这一行:

foo.innerHTML += ' ';
导致问题,移除时,一切正常。 您可以改为使用此选项:

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