Javascript appendChild()显示额外的2行

时间:2014-03-12 02:56:18

标签: javascript html

我有Javascript appendChild()方法可以正常工作,但它会产生两个额外的行。当我单击提交时,如何只显示一行,当我再次输入时显示另一行?

以下是我的Javascript代码?

<html>
<head>
<title>Birth Registration</title>
<script type="text/javascript">
function regBirth(){
  var myArray =[
      sFirstName = { },
      sLastName = { },
      dob ={}
    ]
  myArray[0]=document.getElementById('firstname').value;//myArray[0] is for the first item
  document.getElementById('fname').innerHTML = myArray[0];

  myArray[1]=document.getElementById('lastname').value;
  document.getElementById('lname').innerHTML =  myArray[1];//myArray[1] is for the second item

  myArray[2]=document.getElementById('birthDate').value;
  document.getElementById('dob').innerHTML =  myArray[2];//myArray[2] is for the third item

  results = []
  results[0] = myArray.length;
  document.getElementById("count").innerHTML = results[0] -2;

    fragment = document.createDocumentFragment();
    //Table structure variables
    var tablerow, tdFirstName,tdLastName,tdDateOfBirth;
for (i=0;i<myArray.length;i++){
    var iteration = myArray[i];
        tablerow = document.createElement('tr');
        //first table cell
        myArray[0] = document.createElement('td');
        myArray[0].innerHTML = iteration;
        tablerow.appendChild(myArray[0]);

        //Second table cell
        myArray[1] = document.createElement('td');
        myArray[1].innerHTML = iteration[0];
        tablerow.appendChild(myArray[1]);

        //Third table cell 
        myArray[2] = document.createElement('td');
        myArray[2].innerHTML = iteration[2];
        tablerow.appendChild(myArray[2]);

        //Table row close
        fragment.appendChild(tablerow);


  }

document.getElementById("details").appendChild(fragment);



}
</script>
</head>

<body>
<h1>Birth Registration</h1>
<hr />
<label>First Name:
  <input type='text' id='firstname'  value='Enter your name Here' />
</label>
<label>Last Name:
  <input type='text' id='lastname'   value='Enter your name Here' />
</label>
 <label for="size_1">D.O.B:</label><input type="date" name="size" id="birthDate" value="dd/mm/yy" />
 <hr />
<table id="details">
  <tr>
  <th>First NameName</th>
  <th>Last Name</th>
  <th>Date of Birth</th>
  </tr>


</table>

<input type='button' onclick='regBirth()' value='Submit'/>
<h4>Statistics</h1>
<hr />
<h5>Total Count:</h5><p id="count"></p>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

试试这个:for(i = 0; i&lt; 1; i ++){// code}

答案 1 :(得分:0)

问题是数组长度。它将数组长度设为3.因此,附加两行。 所以将长度减少到1。