最终效果图:

html布局结构代码:
<table border=1 width="500">
<thead>
<tr>
<th>序号</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>成名绝技</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
js实现代码:
// 数据
var arr = [
{
name:"令狐冲",
age:20,
sex:"男",
skill:"独孤九剑"
},
{
name:"东方不败",
age:50,
sex:"女",
skill:"葵花宝典"
},
{
name:"任我行",
age:55,
sex:"男",
skill:"吸星大法"
},
{
name:"乔峰",
age:30,
sex:"男",
skill:"降龙十八掌"
},
{
name:"张无忌",
age:19,
sex:"男",
skill:"九阳神功"
},
{
name:"段誉",
age:22,
sex:"男",
skill:"六脉神剑"
}
];
// 遍历数组
var str = '';
for(var i=0;i<arr.length;i++){
// 判断tr是单行还是双行 - 单行和双行给不同背景颜色
if(i%2){
str += '<tr bgColor="pink">'
}else{
str += '<tr bgColor="skyblue">'
}
str += '<td>'+(i+1)+'</td>'
// 遍历数组中的对象 - 拼接成td
for(var attr in arr[i]){
str += '<td>'
str += arr[i][attr]
str += '</td>'
}
str += '</tr>'
}
// 将最终的str放在tbody中
document.querySelector('tbody').innerHTML = str;
网友评论