我正在练习(来自Beginning Javascript)以更好地理解DOM操作。尝试仅使用JS在DRY方法中重新创建下表(教科书解决方案为here):
SampleLaunch.class
我试过这个,但不确定如何在不抛出错误的情况下循环变量创建:
public class
SampleLaunch
{
public static void main (String args[]) {
SampleGPane sgp = new SampleGPane ();
sgp.launchFrame ();
}
}
答案 0 :(得分:1)
请使用tr
代替tr[i]
。它会起作用
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
}
}
答案 1 :(得分:1)
如上所述,问题是声明tr[i]
变量时的语法错误。
更简洁的方法是使用表格api方法,如
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
});
});
&#13;