简体   繁体   English

更改表格行的颜色onclick

[英]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: 我们假设你的代码是这样的:

HTML HTML

<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>

In that case, you can use jQuery this way: 在这种情况下,您可以这样使用jQuery:

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

And finally the CSS part: 最后是CSS部分:

table tr.active {background: #ccc;}

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

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

Fiddle 小提琴

More elegant solution: 更优雅的解决方案

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

Fiddle 小提琴

Try this demo : 试试这个演示

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

css CSS

.myclass{
background: red;
}

table tr{
 background: yellow;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM