How do I change HTML table cell color on click

旧巷老猫 提交于 2019-11-29 14:09:47

Ugly, but demonstrates the effect:

  <table>
    <tr>
        <td onclick="this.style.backgroundColor = 'Red';">Sample</td>
        <td onclick="this.style.backgroundColor = 'Blue';">Data</td>
    </tr>
  </table>

I'm not well versed in the Prototype framework, but here's some raw Javascript that'll do what you're looking for:

var table = document.getElementsByTagName('table')[0];
if(table) table.onclick = function(e) {
    var target = (e || window.event).target;
    if (target.tagName in {TD:1, TH:1})
        target.setAttribute('style', 'background-color: #F00');
};​

Test it on jsFiddle

You could loop over all the children of the table and add an click event to them

with prototype the code is:

$('your_table').observe('click', function(event) {
  var clickedCell = event.findElement('td');
  if (clickedCell) {
   clickedCell.setStyle({ background: '#dfd' });
  }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!