开发者

Swap table cell color on click

开发者 https://www.devze.com 2023-01-24 10:27 出处:网络
I want to be able to click a table cell, have it switch to color1, and then on the next click have it switch to color2, then back to color1... and so on.

I want to be able to click a table cell, have it switch to color1, and then on the next click have it switch to color2, then back to color1... and so on.

function cSwap(cell){ 
 if (cell.style.backgroundColor = "#00000F")
 {
  cell.style.backgroundColor = "#F00000";
 }
 e开发者_开发知识库lse if (cell.style.backgroundColor = "#F00000")
 {
  cell.style.backgroundColor = "#00000F";
 }
}

Right now, it only changes to the first color, and subsequent clicks do nothing.

The cells of the table each look like this:

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

...which'll be CSS once I get everything working (beside the point).


You need double equals for comparison:

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

or triple equals if you prefer.


Even with double equal signs it won't work. backgroundColor will change its string to an rgb value in Firefox when its value is retrieved (and other browsers may behave alike).

A solution is to put those colors in a class and switch the table cell's class on click. That's also more general, as you can easily change the colors.

CSS:

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

Also, the attribute is called class, not classname. And remember that you cannot have two elements with the same 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>

And the accompanying script:

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

精彩评论

暂无评论...
验证码 换一张
取 消