开发者

Generate a 4 column table from javascript array data

My question is very similar to How to Generate 3x3 HTML Table From an JavaScript Array the only problem is that the answer I prefer in that thread I cant seem to make work (I like it because it does not use innerHTML).

My current code:

var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var tab开发者_如何学JAVAle =  document.createElement("table");
var i = 0;
for (var r = 0; r < 4; r++) {
    var row = table.insertRow();
    for (var c= 0; c < 4; c++) {
        var cell = row.insertCell();
        cell.appendChild(document.createTextNode(alphabet[i++]));
    }
}

document.body.appendChild(table);

Basically when I include this .js file in my html document nothing happens. I tried creating a table and loading it inside of it also, but that did nothing. I am probably missing something obvious here.


Try

window.onload = function() {
  var alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
  var table = document.createElement("table");
  var i = 0;
  for (var r = 0; r < 4; r++) {
    var row = table.insertRow(r);
    for (var c = 0; c < 4; c++) {
      var cell = row.insertCell(c);
      cell.appendChild(document.createTextNode(alphabet[i++]));
    }
  }

  document.body.appendChild(table);
}


Don't just include, put this in onload

<script type="text/javascript">
function load()
{
// your code here
}
</script>
</head>

<body onload="load()">
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜