js 指向表格行变色,离开恢复
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script>
var bgColor;
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');
tr.onmouseover = function () {
bgColor = this.style.backgroundColor;//存储颜色
this.style.backgroundColor = 'yellow';
};
tr.onmouseleave =function(){
this.style.backgroundColor = bgColor;
};
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>
var bgColor;
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');
tr.onmouseover = function () {
bgColor = this.style.backgroundColor;//存储颜色
this.style.backgroundColor = 'yellow';
};
tr.onmouseleave =function(){
this.style.backgroundColor = bgColor;
};
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>