我正在尝试从JSON
数据动态添加表头。
我还需要生成标题(th
),以便不会手动完成。
我有一个非常基本的工作示例:我熟悉JQuery
解决方案,但是,我想用JavaScript方法做到这一点:
一些JSON格式的数据:
var value = [{
"City": "KABUL",
"Continent": "ASIA",
"Country": "AFGHANISTAN",
"CountryAbbr": "AF",
"CountryId": "102120"
}, {
"City": "MARIEHAMN",
"Continent": "EUROPE",
"Country": "ALAND ISLANDS",
"CountryAbbr": "AX",
"CountryId": "102115"
}];
JavaScript的:
var out = "<table>";
for ( var i = 0; i < value.length; i++) {
out += "<tr><td>" + value[i].Country +
"</td><td>" + value[i].City +
"</td><td>" + value[i].CountryAbbr +
"</td></tr>";
}
out += "</table>";
document.getElementById("tableContainer").innerHTML = out;
HTML:
<div id="tableContainer"></div>
答案 0 :(得分:0)
如果您正在谈论表格标题/标题,那么下面的代码对您有帮助:
var value = [{
"City": "KABUL",
"Continent": "ASIA",
"Country": "AFGHANISTAN",
"CountryAbbr": "AF",
"CountryId": "102120"
}, {
"City": "MARIEHAMN",
"Continent": "EUROPE",
"Country": "ALAND ISLANDS",
"CountryAbbr": "AX",
"CountryId": "102115"
}];
var out = "<table>";
out+="<tr><th>Country</th><th>City</th><th>Country Code</th></tr>";//TABLE HEADER/HEADING----------
for ( var i = 0; i < value.length; i++ ) {
out += "<tr><td>" + value[i].Country +
"</td><td>" + value[i].City +
"</td><td>" + value[i].CountryAbbr +
"</td></tr>";
}
out += "</table>";
document.getElementById("tableContainer").innerHTML = out;