简体   繁体   English

如何在javascript中更改表格单元格的颜色

[英]How to change the color of a cell of a table in javascript

This is my function 这是我的功能

<script>
  function colorChange() {
     document.getElementById('change').bgcolor="#00CC99";
  }
</script>

and this is my table 这是我的桌子

 <?php>

 echo("<table border=\"1\" cellpadding=\"5\"><tr>\n");
 if($dayArray["month"] == $mydate[month])
 {
   echo ("<td id=\"change\" bgcolor=\"#FF99FF\">
   <a href=\"javascript:colorChange()\"</a>")></td>\n");
  } 
 echo (</table>);

but the color of the cell does not change. 但细胞的颜色不会改变。 Can anybody help me? 有谁能够帮助我?

There's no such property as bgcolor , there is however an attribute, but you should use element.style : 没有像bgcolor这样的属性,但是有一个属性,但你应该使用element.style:

document.getElementById('change').style.background = "#00CC99";

or 要么

document.getElementById('change').style.backgroundColor = "#00CC99";

or if you just have to change the attribute 或者,如果您只需要更改属性

document.getElementById('change').setAttribute('bgcolor', '#00CC99');

Your code looks very messy with html embedded inside php echo statements. 使用嵌入在php echo语句中的html你的代码看起来非常混乱。 Change this too: 改变这个:

<table border="1" cellpadding="5"><tr>
<?php
if($dayArray["month"] == $mydate[month])
{
?>
 <td id="change" style="background:#FF99FF"><a href="javascript:colorChange()">></a></td>
 <?php
  } 
 ?>
</tr>
</table>

Javascript: 使用Javascript:

//There is no property called 'bgcolor', use style.backgroundColor instead.

function colorChange(){
document.getElementById('change').style.backgroundColor="#00CC99"; bgcolor
}

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM