I have an array that looks like this (the full list is here):
var verbMap = [
{
infinitive: "gehen",
thirdPres: "geht",
thirdPast: "ging",
aux: "ist",
pastPart: "gegangen",
english: "go"
},
{
infinitive: "gelingen",
thirdPres: "gelingt",
thirdPast: "gelang",
aux: "ist",
pastPart: "gelungen",
english: "succeed"
}
];
I am trying to run through each part and print it into a table. I can access one of the values if I target it specifically, but I need to be able to print all of the values into <td>
s. Each part of the array would be a <tr>
with the values inside as the <td>
tags.
What would be the best way to do this, and is there a better way to set the dat开发者_C百科a up and interact with it?
It shouldn't be too hard to create the table using nested for loops (the example uses jQuery to build the elements...but you obviously don't have to):
Edit
Removed the jQuery since it seemed to bother everybody (even though the control structures were the important part of the example):
var table = document.createElement('table');
for(v in verbMap){
var tr = document.createElement('tr');
for(p in verbMap[v]){
var td = document.createElement('td');
var text = document.createTextNode(verbMap[v][p]);
td.appendChild(text);
tr.appendChild(td);
}
table.appendChild(tr);
}
Try the following
for (var i = 0; i < verbMath.length; i++) {
var row = document.createElement('tr');
var item = verbMath[i];
for (var prop in item) {
if (item.hasOwnProperty(prop)) {
var data = document.createElement('td');
data.innerText = item[prop];
row.appendChild(data);
}
}
// Need to append the row here to the appropriate place in your DOM
}
Firefox doesn't support innerText
so it's better to create a text node and add that to the child. It may also be better to define an array to guarantee an order of the columns and easily change it if necessary.
var table = document.getElementById("tbl"), i, j, tr, td, text;
var order = ["infinitive", "thirdPres", "thirdPast", "aux", "pastPart", "english"]
for(i=0; i<verbMap.length; i++){
tr = document.createElement('tr');
for(j = 0; j<order.length; j++){
td = document.createElement('td');
text = document.createTextNode(verbMap[i][order[j]]);
td.appendChild(text);
tr.appendChild(td);
}
table.appendChild(tr);
}
JSFiddle
There are some very good tools for creating tables from such data structures. Consider using jQuery and the Datatables plug in.
Here are some links:
jQuery: http://jquery.com/
Datatables: http://datatables.net/
精彩评论