更改表格行的颜色onclick

我创建了一个具有交替颜色(例如黄色和红色)的行的表。 现在,我想将单击行的颜色更改为一种常用颜色(比如蓝色)。再次单击时,还原为原始颜色。 我可以使用此代码更改颜色

$("#mainTable").find('#'+IDClicked).css("background-color", "#bbbbff"); 

我无法弄清楚如何恢复。

我们这种方式假设您的代码:

HTML

 
Cell Cell Cell Cell
Cell Cell Cell Cell
Cell Cell Cell Cell

在这种情况下,您可以这样使用jQuery:

 $(document).ready(function(){ $("#rowClick > tr").click(function(){ $(this).toggleClass("active"); }); }); 

最后是CSS部分:

 table tr.active {background: #ccc;} 

小提琴: http : //jsbin.com/icusec/2

试试以下代码

CSS

 .high-light{background:blue !important;} 

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

完全回答你的问题:

 $('#box').on('click', function() { var box$ = $(this), isBgColorChanged = box$.data('isBgColorChanged'), bgColor = !!isBgColorChanged ? '#444' : '#ccc'; box$.css('background-color', bgColor) .data('isBgColorChanged', !isBgColorChanged); });​ 

小提琴

更优雅的解决方案

 $('#box').on('click', function() { $(this).toggleClass('activated'); });​ 

小提琴

试试这个演示

 $('table tr').toggle(function(){ $(this).addClass('myclass'); }, function(){ $(this).removeClass('myclass'); });​ 

CSS

 .myclass{ background: red; } table tr{ background: yellow; }