2010-11-08 46 views
0

我希望能够单击表格单元格,将其切换到color1,然后在下一次单击时将它切换到color2,然后返回到color1 ...等等。单击时交换表格单元格颜色

function cSwap(cell){ 
if (cell.style.backgroundColor = "#00000F") 
{ 
    cell.style.backgroundColor = "#F00000"; 
} 
else if (cell.style.backgroundColor = "#F00000") 
{ 
    cell.style.backgroundColor = "#00000F"; 
} 
} 

现在,它只是变成第一种颜色,随后的点击什么都不做。

的每个表的细胞是这样的:

<td classname='t' onclick='cSwap(this);' width='100' height='100' id='nw'><a href="" id="nw"></a></td> 

... which'll是CSS一旦我得到一切工作(跑题了)。

+0

抱歉,他们实际上是不同的。我只是碰巧抓住那个。 – xelab 2010-11-08 00:34:31

回答

2

即使有双等号也不行。 backgroundColor将在检索到其值时(和其他浏览器可能表现相似)将其字符串更改为Firefox中的rgb值。

一种解决方案是将这些颜色放在一个类中,并在点击时切换表格单元格的类。这也更一般,因为您可以轻松更改颜色。

CSS:

.t { background: #00f } 
.t2 { background: #f00 } 

此外,属性被称为class,不classname。请记住,你不能有相同的ID两个元素:

<td class='t' onclick='cSwap(this)' width='100' height='100'><a href=""></a></td> 
<td class='t' onclick='cSwap(this)' width='100' height='100'><a href=""></a></td> 

和附带的脚本:

function cSwap(cell){ 
    if (cell.className == "t") 
     cell.className = "t2"; 
    else if (cell.className == "t2") 
     cell.className = "t"; 
} 
+0

完美!谢谢你一堆。 – xelab 2010-11-08 00:57:20

3

你需要双等于作比较:

if (cell.style.backgroundColor == "#00000F") 

triple如果你喜欢平等的。

+0

+1好点... – 2010-11-08 00:25:25