点击时更改表格行的颜色

3

我创建了一个表格,其中的行是交替着颜色的(比如黄色和红色)。现在,我想要将点击的行的颜色更改为一种共同的颜色(比如蓝色),再次点击时恢复原来的颜色。

使用以下代码可以更改颜色:

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

我不知道如何恢复原样。
4个回答

10
我们假设您的代码是这样的:

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>

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

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

最后是CSS部分:

table tr.active {background: #ccc;}

Fiddle: http://jsbin.com/icusec/2


哇!!你回答得真快..但我接受不够快! :) 完美解决..谢谢! - Prathiba
当然可以... :) 欢迎,我已经添加了fiddle! :) - Praveen Kumar Purushothaman
没有 jQuery? - Sith2021
@Sith2021 有很多方法可以使用 document.querySelectorAll 来实现... :) - Praveen Kumar Purushothaman

3
请尝试以下代码:

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

3
回答您的问题:
$('#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');
});​

Fiddle


2

试试这个演示

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

css

.myclass{
background: red;
}

table tr{
 background: yellow;
}

1
你可以使用 toggleClass(),它只是做同样的事情! - Praveen Kumar Purushothaman
@PraveenKumar,我只是想知道哪个方案能够更快地执行和更好地解决问题? - Pragnesh Chauhan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接