我还没有这样做。但是我将如何向表中添加一行呢?这是我目前拥有的:
index.ejs
<table id="addressTable" class='table-primary table-bordered table' style='border-spacing: 10px;'>
<tr>
<td></td>
<td>Street Address:</td>
<td>City</td>
<td>State</td>
<td>Zip Code</td>
<td>Residency Length (years)</td>
</tr>
<tr>
<td>Current Address</td>
<td><input type="string" id="currentStreetAddress" name="currentStreetAddress" placeholder="Current Street Address"/></td>
<td><input type="string" id="currentCity" name="currentCity" placeholder="Current City"/></td>
<td><input type="string" id="currentState" name="currentState" placeholder="Current State"/></td>
<td><input type="number" id="currentZip" name="currentZip" placeholder="Current Zip Code"/></td>
<td><input type="number" id="currentLength" name="currentLength" placeholder="Current Residency Length"/></td>
</tr>
<tr>
<td>Mailing Address</td>
<td><input type="string" id="mailingStreetAddress" name="mailingStreetAddress" placeholder="Mailing Street Address"/></td>
<td><input type="string" id="mailingCity" name="mailingCity" placeholder="Mailing City"/></td>
<td><input type="string" id="mailingState" name="mailingState" placeholder="Mailing State"/></td>
<td><input type="number" id="mailingZip" name="mailingZip" placeholder="Mailing Zip Code"/></td>
<td><input type="number" id="mailingLength" name="mailingLength" placeholder="Mailing Residency Length"/></td>
</tr>
</table>
<button type='button' onclick="addRowAddress()" class="btn btn-primary">Add Row</button><br /><br />
addRow.js
function addRowAddress(){
var empTab = document.getElementById('addressTable');
var addAddress = '<tr><td>Previous Address</td><td><input type="string" id="previousStreetAddress" name="previousStreetAddress" placeholder="Previous Street Address"/></td><td><input type="string" id="previousCity" name="previousCity" placeholder="Previous City"/></td><td><input type="string" id="previousState" name="previousState" placeholder="Previous State"/></td><td><input type="number" id="previousZip" name="previousZip" placeholder="Previous Zip Code"/></td><td><input type="number" id="previousLength" name="previousLength" placeholder="Previous Residency Length"/></td></tr>'
empTab.append(addAddress);
}
当我单击addRow按钮时,它将所有HTML输出为字符串,而不是使用HTML添加到表中。我在做错什么吗?
如果要在tbody中添加一行,请获取对其的引用并将其添加到其中。
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
// Insert a row in the table at the last row
var newRow = tableRef.insertRow();
// Insert a cell in the row at index 0
var newCell = newRow.insertCell(0);
// Append a text node to the cell
var newText = document.createTextNode('New row');
newCell.appendChild(newText);