【发布时间】:2011-08-27 20:54:35
【问题描述】:
我有一个问题: 我需要一个 7x48 单元格的表格,这些单元格具有背景颜色(灰色),单击时必须可切换(绿色),然后再次单击即可再次切换。 我使用以下 js 函数创建了表:
function createGrid(){
// get the reference for the body
var grid = document.getElementById("grid");
var green="#33CC66";
var grey="#DEDEDE";
// creates a <table> element and a <tbody> element
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
tbl.id="timegrid";
tbl.style.backgroundColor=grey;
// creating all cells
for (var j = 0; j < 7; j++) {
// creates a table row
var row = document.createElement("tr");
for (var i = 0; i < 48; i++) {
// Create a <td> element and a text node, make the text
// node the contents of the <td>, and put the <td> at
// the end of the table row
var cell = document.createElement("td");
cell.onmousedown=function(){
if(this.style.backgroundColor!=grey)
this.style.backgroundColor=grey;
else this.style.backgroundColor=green;
};
row.appendChild(cell);
}
// add the row to the end of the table body
tblBody.appendChild(row);
}
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <div id="grid">
grid.appendChild(tbl);
tbl.setAttribute("cellPadding", "7");
tbl.setAttribute("cellSpacing", "0");
tbl.setAttribute("border", "1");}
问题是:它第一次工作(从灰色单元格切换到绿色)但我第二次单击同一个单元格时无法返回原始颜色。 有什么建议吗?
【问题讨论】:
标签: javascript html-table cell background-color