js 生成表格及其颜色
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script>
onload = function () {
var list = [
{ id: '1', country: '中国', capital: '北京' },
{ id: '2', country: '美国', capital: '华盛顿' },
{ id: '3', country: '日本', capital: '东京' },
{ id: '4', country: '韩国', capital: '首尔' }
];
var body = document.getElementsByTagName('body')[0];
var table = document.createElement('table');
table.border = '1px solid red';
body.appendChild(table);
var thead = document.createElement('thead');
table.appendChild(thead);
var item0 = list[0];
for (var key in item0) {
var tdh = document.createElement('td');
tdh.innerHTML = key;
thead.appendChild(tdh);
}
for (var i = 0; i < list.length; i++) {
var tr = document.createElement('tr');
if (i % 2 == 0) {
tr.style.backgroundColor = 'yellow';
} else {
tr.style.backgroundColor = 'lightBlue';
}
table.appendChild(tr);
var item = list[i];
for (var key in item) {
var td = document.createElement('td');
td.innerHTML = item[key];
tr.appendChild(td);
}
}
}
</script>
</head>
<body>
</body>
</html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script>
onload = function () {
var list = [
{ id: '1', country: '中国', capital: '北京' },
{ id: '2', country: '美国', capital: '华盛顿' },
{ id: '3', country: '日本', capital: '东京' },
{ id: '4', country: '韩国', capital: '首尔' }
];
var body = document.getElementsByTagName('body')[0];
var table = document.createElement('table');
table.border = '1px solid red';
body.appendChild(table);
var thead = document.createElement('thead');
table.appendChild(thead);
var item0 = list[0];
for (var key in item0) {
var tdh = document.createElement('td');
tdh.innerHTML = key;
thead.appendChild(tdh);
}
for (var i = 0; i < list.length; i++) {
var tr = document.createElement('tr');
if (i % 2 == 0) {
tr.style.backgroundColor = 'yellow';
} else {
tr.style.backgroundColor = 'lightBlue';
}
table.appendChild(tr);
var item = list[i];
for (var key in item) {
var td = document.createElement('td');
td.innerHTML = item[key];
tr.appendChild(td);
}
}
}
</script>
</head>
<body>
</body>
</html>