4

我尝试运行 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>   
4

3 回答 3

2

我会改变这个 -

var cell1  =  document.createElement('td').innerHTML = 'foods[i]'; 

var cell1  =  document.createElement('td');
cell1.innerHTML = 'foods[i]'; 

当您将其 innerHTML 内联链接到 cell1 时,我不希望 cell1 会正确设置,但尚未对其进行测试。

于 2012-12-27T21:30:16.147 回答
1

像这样的东西会遍历你的数组并创建一行,因为这似乎是你想要做的。

var foods = ["milk", "eggs", "lettuce", "tomato"],
    food,
    row = document.createElement("tr");

while (food = foods.shift()) {
    var el = document.createElement("td");
        el.innerText = food;

    row.appendChild( el );
}

document.getElementsByTagName("table")[0].appendChild(row);
于 2012-12-27T21:31:50.917 回答
1

您的代码中有几个错误,包括for循环周围缺少大括号和第 6 行看起来很奇怪的'enter code here'句子。您还忘记将 JavaScript 代码放入<script>标签中。这是您的代码的工作版本:

<script>
function addtd(){
    var table1 = document.getElementsByTagName('table')[0];
    var rowrow =  document.createElement('tr');
    var foods = new Array();

    foods[0] = "milk" ;
    foods[1] = "meat" ;
    foods[2] = "fruit" ;
    foods[3] = "fish" ;
    foods[4] = "salad" ;

    for ( i=0; i <foods.length; i++) {
        var cell1  =  document.createElement('td');
        var text1 = document.createTextNode(foods[i]);
        cell1.appendChild(text1);
        rowrow.appendChild(cell1);
    }
    table1.appendChild(rowrow);
}
</script>

<div id="divfood"> </div>
<button onclick="addtd()">Click me</button>
<table border="2" id="tabletable" cellspacing="5" >
</table>   ​

这是jsFiddle 演示

于 2012-12-28T09:31:50.630 回答