2011-05-18 55 views
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");} 

的問題是:它的工作原理與第一時間(從灰小區切換到綠色),但我不能回頭到原始顏色的第二時間我點擊同一個單元格。 有什麼建議嗎?

回答

2

問題是瀏覽器不會保持您設置的相同值。

例如,如果你做

document.body.style.backgroundColor = '#33cc66' 
console.log(document.body.style.backgroundColor); 

你得到rgb(51, 204, 102)返回。 (並且讓我們知道StackOverflow是醜陋的帶有綠色背景。)

此值爲functional notation for colour

您可能需要存儲您設置的值,因爲瀏覽器報告當前顏色值的方式不一致。

cell.onmousedown=function(){ 
    if(background !== grey) { 
     this.style.backgroundColor=grey; 
     background = grey; 
    } else { 
     this.style.backgroundColor=green;  
     background = green;    
    } 
}; 
+0

感謝您的答案,但我只是用類名,而不是宣佈細胞的風格JS解決:\t如果(this.className ==「greenCell」)this.className =「greyCell」; else this.className =「greenCell」; – breathe0 2011-05-18 09:11:37

+0

@ breathe0沒問題。如果答案解決了您的問題,您可以[標記爲已接受](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)。 – lonesomeday 2011-05-18 09:13:39

相關問題