我有一个函数来改变我的HTML表格中单击行的背景颜色,但是当我加载页面时,我必须在一行中单击两次以更改她的颜色。JavaScript:为什么我必须在表格中单击两次以执行colorActiveLine函数?
当我已经改变了一条线的背景颜色时,它没问题。我只能点击一次来改变颜色。 只有当我刚刚加载页面时,问题才出现。
这里我的问题的一个例子:
HTML
<html>
<head>
<script type="text/javascript" src="main.js"></script>
<style media="screen" type="text/css">
table {border-collapse: collapse;} tr {border: 1px solid;} td {border: 1px solid;}
</style>
</head>
<body onload="populateTable()">
<table>
<tbody id="fruitTable">
</tbody>
</table>
</body>
</html>
的JavaScript
// POPULATE THE TABLE ON LOAD WITH SOME DATA
function populateTable() {
var tableRef = document.getElementById('fruitTable');
var newRow;
var newCell1;
var newCell2;
// ADD LINE 1
newRow = tableRef.insertRow(-1);
newRow.style.background = '#98A2DD';
newRow.onclick = colorActiveLine;
newCell1 = newRow.insertCell(0);
newCell2 = newRow.insertCell(1);
newCell1.innerHTML = "apple";
newCell2.innerHTML = "green";
// ADD LINE 2
newRow = tableRef.insertRow(-1);
newRow.style.background = '#98A2DD';
newRow.onclick = colorActiveLine;
newCell1 = newRow.insertCell(0);
newCell2 = newRow.insertCell(1);
newCell1.innerHTML = "banana";
newCell2.innerHTML = "yellow";
// ADD LINE 3
newRow = tableRef.insertRow(-1);
newRow.style.background = '#98A2DD';
newRow.onclick = colorActiveLine;
newCell1 = newRow.insertCell(0);
newCell2 = newRow.insertCell(1);
newCell1.innerHTML = "coconut";
newCell2.innerHTML = "white";
}
// CHANGE BACKGROUND COLOR ON CLICK
function colorActiveLine() {
var lines = document.getElementsByTagName('tr');
for (var i = 0; i < lines.length; ++i) {
lines[i].onclick = function() {
// SET ALL BACKGROUND COLOR TO BLUE
for (var j = 0; j < lines.length; ++j) {
lines[j].style.background = '#98A2DD';
};
// SET ALL BACKGROUND COLOR TO ORANGE
this.style.background = '#DDC498';
};
}
}
在此先感谢。