简体   繁体   中英

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 table =  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()">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM