Javascript 如何在单击时更改 HTML 表格单元格颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3722465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I change HTML table cell color on click
提问by Rohan
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.
当用户单击单元格时,我试图更改 HTML 表格单元格的背景颜色。关于如何做到这一点的任何想法?我可以访问 JS Prototype 库,因此欢迎对 Prototype 或直接 Javascript 提出任何建议。
回答by Larsenal
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>
回答by Kevin
I'm not well versed in the Prototype framework, but here's some raw Javascript that'll do what you're looking for:
我不太熟悉 Prototype 框架,但这里有一些原始的 Javascript 可以满足您的需求:
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
回答by lock
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' });
}
});