我尝试运行 Javascript 循环以从数组中创建一个包含值的表:我附加了文本节点并尝试将文本节点作为数组值,每个 td 一个长度。到目前为止,这是我的代码,它只会创建一个具有“未定义”值的单元格:
function addtd(){
var table1 = document.getElementsByTagName('table')[0];
var rowrow = document.createElement('tr');
var foods = new Array();
foods[0] = "milk" ;`enter code here`
foods[1] = "meat" ;
foods[2] = "fruit" ;
foods[3] = "fish" ;
foods[4] = "salad" ;
for ( var i=0;i<foods.length;i++)
var cell1 = document.createElement('td').innerHTML = 'foods[i]';
var text1 = document.createTextNode(foods[i]) ;
cell1.appendChild(text1);
rowrow.appendChild(cell1);
table1.appendChild(rowrow);
}
<div id="divfood"> </div>
<button onclick="addtd()">Click me</button>`enter code here`
<table border="2" id="tabletable" cellspacing="5" >
</table>