jQuery - OnClick,单击时始终更改表格单元格的背景颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19618169/
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
jQuery - OnClick, change background color for table cells always when clicked
提问by Karol
For example: You have a table, and it has 4 tds and 2 trs. Table's background color is white. If i click to A td, A td should be red, than if i click to B, B td should be red and A td should be red too. If i click to C than, C should be red and B and A should be red too.
例如:您有一张桌子,它有 4 个 tds 和 2 个 trs。表格的背景颜色为白色。如果我点击 A td,A td 应该是红色的,而不是如果我点击 B,B td 应该是红色的,A td 也应该是红色的。如果我点击 C 比,C 应该是红色的,B 和 A 也应该是红色的。
I have something like this. But it isnt good, because when i click again i want to change color back to white.
我有这样的事情。但这并不好,因为当我再次单击时,我想将颜色改回白色。
http://jsfiddle.net/k8UgT/193/
http://jsfiddle.net/k8UgT/193/
The code i use
我使用的代码
<table>
<tr>
<td onclick="function()">AAA</td>
<td onclick="function()">BBB</td>
<td onclick="function()">CCC</td>
</tr>
<tr>
<td onclick="function()">DDD</td>
<td onclick="function()">EEE</td>
<td onclick="function()">FFF</td>
</tr>
</table>
JS:
JS:
$( function() {
$('td').click( function() {
$(this).css('background', '#aaa')
} );
} );
回答by Hugo Tunius
Welcome to SO.
欢迎来到 SO。
First of all you don't need to onclick
attribute on the td's. Second of all I would suggest using a CSS class instead of setting the background color.
首先,您不需要onclick
归因于 td。其次,我建议使用 CSS 类而不是设置背景颜色。
CSS
CSS
.red-cell {
background: #F00; /* Or some other color */
}
JS
JS
$( function() {
$('td').click( function() {
$(this).toggleClass("red-cell");
} );
} );
回答by techfoobar
Use a CSS class for the red background and then use .toggleClass()
in your JavaScript.
为红色背景使用 CSS 类,然后.toggleClass()
在您的 JavaScript 中使用。
JavaScript
JavaScript
$('td').click( function() {
$(this).toggleClass('on');
});
CSS
CSS
td.on {
background-color: red;
}
回答by Rasool Ghafari
try this:
尝试这个:
$( function() {
$('td').click( function() {
if($(this).attr('style'))
$(this).removeAttr('style');
else
$(this).css('background', '#aaa')
} );
} );
回答by Anto Subash
try this
尝试这个
$( function() {
$('td').toggle( function() {
$(this).css('background', 'red');
},function(){
$(this).css('background', 'white');
});
} );
here is the fiddle http://jsfiddle.net/k8UgT/199/