HTML:
<table class="bingo">
<tr>
<td id="square0"></td>
<td id="square1"></td>
<td id="square2"></td>
</tr>
<tr>
<td id="square3"></td>
<td id="square4"></td>
<td id="square5"></td>
</tr>
<tr>
<td id="square6"></td>
<td id="square7"></td>
<td id="square8"></td>
</tr>
</table>
JS:
var toggleHighlight = function (e) {
var bg = e.target.style.backgroundColor;
if (bg == 'red') {
e.target.style.backgroundColor = '';
} else {
e.target.style.backgroundColor = 'red';
}
}
var prepareTable = function () {
var cells = document.getElementsByTagName("td");
for (var i = 0 ; i < cells.length ; i++) {
cells[i].onclick = function(event) {
toggleHighlight(event);
}
}
}
document.onload = prepareTable();
上面的代码在这里演示: http://jsfiddle.net/nyzswnx2/47/
然而,当我将红色变为#cecece时,我能够点击每个细胞,将细胞从白色变为浅灰色。但是,当我再次单击浅灰色单元格时,它不会将单元格从浅灰色变为白色。我该如何解决这个问题?
http://jsfiddle.net/RE006/nyzswnx2/82/
// e is parameter
var toggleHighlight = function (e) {
var bg = e.target.style.backgroundColor;
if (bg == "#cecece") {
e.target.style.backgroundColor = "#fff";
} else {
e.target.style.backgroundColor = "#cecece";
}
}
/* getting a list from "td" will return a list, it is need for a loop to store the cells passes event as argument */
var prepareTable = function () {
var cells = document.getElementsByTagName("td");
for (var i = 0 ; i < cells.length ; i++) {
cells[i].onclick = function(event) {
toggleHighlight(event);
}
}
}
//calls the function
document.onload = prepareTable();
答案 0 :(得分:0)
var bg = e.target.style.backgroundColor;
backgroundColor以rgb而不是hex的形式返回。 bg
的值为rgb(206, 206, 206)
,而不是#cecece
您可以尝试比较rgb字符串或首先将值转换为十六进制。
if (bg == "rgb(206, 206, 206)") {