How do I change HTML table cell color on click

六眼飞鱼酱① 提交于 2019-12-18 08:33:09

问题


I'm trying to change the background color of an HTML table cell when the user clicks on the cell. Any ideas on how to do this? I have access to the JS Prototype library, so any suggestions for Prototype or straight Javascript would be welcome.


回答1:


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>



回答2:


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




回答3:


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' });
  }
});


来源:https://stackoverflow.com/questions/3722465/how-do-i-change-html-table-cell-color-on-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!