问题
I am doing an exercise (from Beginning Javascript) to better understand DOM manipulation. Attempting to recreate the following table in a DRY method using only JS (the textbook solution is here):
<table>
<tr>
<td>Car</td>
<td>Top Speed</td>
<td>Price</td>
</tr>
<tr>
<td>Chevrolet</td>
<td>120mph</td>
<td>$10,000</td>
</tr>
<tr>
<td>Pontiac</td>
<td>140mph</td>
<td>$20,000</td>
</tr>
</table>
I tried this but unsure how you can loop variable creation without throwing an error:
var array = [['Car', 'Top Speed', 'Price'],['Chevrolet', '120mph', '$10,000'], ['Pontiac', '140pmh', '$20,000']] // Creating a data array which a loop will source from
var table = document.createElement('table');
document.body.appendChild(table); // Drew the main table node on the document
for (var i = 0; i<3; i++) {
var tr[i] = document.createElement('tr'); //Create 3 <tr> elements assigned to a unique variable BUT need a working alternative for 'tr[i]'
table.appendChild(tr[i]); // Append to <table> node
for (var j = 0; j<3; j++) {
var tdText = document.createTextNode(array[i][j]); // Extract data from array to a placeholder variable
tr[i].appendChild(tdText); // Take string from placeholder variable and append it to <tr> node
}
}
回答1:
Please use tr
instead of tr[i]
. It will work
var array = [['Car', 'Top Speed', 'Price'],['Chevrolet', '120mph', '$10,000'], ['Pontiac', '140pmh', '$20,000']] // Creating a data array which a loop will source from
var table = document.createElement('table');
document.body.appendChild(table); // Drew the main table node on the document
for (var i = 0; i<3; i++) {
var tr = document.createElement('tr'); //Create 3 <tr> elements assigned to a unique variable BUT need a working alternative for 'tr[i]'
table.appendChild(tr); // Append to <table> node
for (var j = 0; j<3; j++) {
var tdElement = document.createElement('td');
tdElement.innerHTML = array[i][j];
tr.appendChild(tdElement); // Take string from placeholder variable and append it to <tr> node
}
}
回答2:
As already said the problem is the syntax error in declaring the tr[i]
variable.
A more cleaner way will be is to use the table api methods like
var array = [
['Car', 'Top Speed', 'Price'],
['Chevrolet', '120mph', '$10,000'],
['Pontiac', '140pmh', '$20,000']
] // Creating a data array which a loop will source from
var table = document.createElement('table');
document.body.appendChild(table); // Drew the main table node on the document
array.forEach(function(row) {
var tr = table.insertRow(); //Create a new row
row.forEach(function(column) {
var td = tr.insertCell();
td.innerText = column; // Take string from placeholder variable and append it to <tr> node
});
});
- HTMLTableElement
- insertRow()
- insertCell
来源:https://stackoverflow.com/questions/35617964/drawing-a-table-with-vanilla-js-and-loops