[英]Change colour of table row onclick
I have created a table having rows with alternating colours(say yellow and red). 我已经创建了一个具有交替颜色(例如黄色和红色)的行的表。 Now, I want to change the colour of the clicked row to one common colour(say blue).And revert back to its original colour when clicked again.
现在,我想将单击行的颜色更改为一种常用颜色(比如蓝色)。再次单击时,还原为原始颜色。 I'm able to change the colour using this code
我可以使用此代码更改颜色
$("#mainTable").find('#'+IDClicked).css("background-color", "#bbbbff");
I'm not able to figure out how to revert back. 我无法弄清楚如何恢复。
We assume that your code this this way: 我们假设你的代码是这样的:
<table id="rowClick">
<tr>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
</tr>
<tr>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
</tr>
<tr>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
</tr>
</table>
$(document).ready(function(){
$("#rowClick > tr").click(function(){
$(this).toggleClass("active");
});
});
table tr.active {background: #ccc;}
Try this below code 请尝试以下代码
CSS CSS
.high-light{background:blue !important;}
jQuery jQuery的
$(document).ready(function(){
$('table tr').click(function(){ $(this).addClass("high-light"); });
//If you have TD's background set try the below commented code
$('table tr td').click(function(){ $(this).parent().find('td').addClass("high-light"); });
});
Answering exactly to your question: 完全回答你的问题:
$('#box').on('click', function() {
var box$ = $(this),
isBgColorChanged = box$.data('isBgColorChanged'),
bgColor = !!isBgColorChanged ? '#444' : '#ccc';
box$.css('background-color', bgColor)
.data('isBgColorChanged', !isBgColorChanged);
});
More elegant solution: 更优雅的解决方案
$('#box').on('click', function() {
$(this).toggleClass('activated');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.