2
我遇到問題: 我需要一個表格7x48單元格,這些單元格具有背景顏色(灰色),點擊時必須可切換(綠色),然後再次切換再次點擊。 我所創建的表具有以下js函數:切換使用javascript創建的表格的單元格背景顏色
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");}
的問題是:它的工作原理與第一時間(從灰小區切換到綠色),但我不能回頭到原始顏色的第二時間我點擊同一個單元格。 有什麼建議嗎?
感謝您的答案,但我只是用類名,而不是宣佈細胞的風格JS解決:\t如果(this.className ==「greenCell」)this.className =「greyCell」; else this.className =「greenCell」; – breathe0 2011-05-18 09:11:37
@ breathe0沒問題。如果答案解決了您的問題,您可以[標記爲已接受](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)。 – lonesomeday 2011-05-18 09:13:39