js實現表格隔行換色
阿新 • • 發佈:2022-04-19
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
*{
padding: 0;
margin: 0;
}
table{
margin: 50px auto;
}
</style>
<body>
<table border=1 width="500">
<thead>
<tr>
<th>序號</th>
<th>姓名</th>
<th>年齡</th>
<th>性別</th>
<th>成名絕技</th>
</tr>
</thead>
</table>
</body>
<script>
var arr = [
{
name:"令狐沖",
age:20,
sex:"男",
skill:"獨孤九劍"
},
{
name:"東方不敗",
age:30,
sex:"女",
skill:"葵花寶典"
},
{
name:"任我行",
age:80,
sex:"男",
skill:"吸星大法"
},
{
name:"喬峰",
age:30,
sex:"男",
skill:"降龍十八掌"
},
{
name:"張無忌",
age:25,
sex:"男",
skill:"九陽神功"
},
{
name:"段譽",
age:22,
sex:"男",
skill:"六脈神劍"
}
];
var tbody = document.createElement('tbody');
var table = document.querySelector('table');
table.appendChild(tbody);
var str = ''
arr.forEach(function(v,i){
if(i%2){
str += '<tr bgColor="skyblue">'
}else{
str += '<tr bgColor="pink">'
}
str += '<td>'+(i+1)+'</td>' for(var key in v) { str += '<td>'+v[key]+'</td>' } str += '</tr>' }) tbody.innerHTML = str </script> </html> 效果圖:
str += '<td>'+(i+1)+'</td>' for(var key in v) { str += '<td>'+v[key]+'</td>' } str += '</tr>' }) tbody.innerHTML = str </script> </html> 效果圖: