如何从JSON数据生成HTML表?
我有以下JSON数据:
[
{
name: "Condition"
value: "New"
},
{
name: "Year"
value: "2007"
},
{
name: "Manufacturer"
value: "Audi"
},
{
name: "Model"
value: "A4"
},
{
name: "Type"
value: "Limousine"
},
{
name: "Options"
value: "Full"
}
]
我想生成一个像这样的html表:
<table width="779" border="1" cellpadding="0" cellspacing="0">
<tr>
<td width="104">Condition</td>
<td width="318">New</td>
<td width="176">Year</td>
<td width="171">2007</td>
</tr>
<tr>
<td>Manufacturer</td>
<td>Audi</td>
<td>Model</td>
<td>A4</td>
</tr>
<tr>
<td>Type</td>
<td>Limousine</td>
<td>Options</td>
<td>Full</td>
</tr>
</table>
我需要每行2个对象。 在两个对象创建具有下两个对象的新行之后,依此类推。
答案 0 :(得分:0)
您的JSON数据格式不是最新的,您需要添加&#39;,&#39;之前的价值&#39;索引。
<!DOCTYPE HTML>
<html lang = "zh">
<head>
<meta charset="utf-8" />
<title>
jQuery Table
</title>
<script src="js/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div id = "divTable"></div>
<script>
var data = [
{
name: "Condition"
, value: "New"
},
{
name: "Year"
, value: "2007"
},
{
name: "Manufacturer"
, value: "Audi"
},
{
name: "Model"
, value: "A4"
},
{
name: "Type"
, value: "Limousine"
},
{
name: "Options"
, value: "Full"
}
];
var html = '<table width="779" border="1" cellpadding="0" cellspacing="0">';
html += '<tr><td width="104">' + data[0].name + '</td><td width="318">' + data[0].value + '</td>';
html += '<td width="176">' + data[1].name + '</td><td width="171">' + data[1].value + '</td></tr>';
for(var i = 2; i < data.length; i++) {
if(i % 2 == 0)
html += '<tr>';
html += createEleHtml(data[i]);
if(i % 2 == 1)
html += '</tr>';
}
function createEleHtml(ele){
if(ele && ele.name) return '<td>' + ele.name + '</td><td>' + ele.value + '</td>';
};
html += '</table>';
$("#divTable").html(html);
</script>
</body>
</html>