突出显示条带化HTML表格的单击行

dum*_*ter 41 javascript css

这是我在jsFiddle问题的一个例子.

我有一个带有tr:nth-child(odd)在CSS中使用的条带行的表,就像在table-striped类的Twitter Bootstrap中一样.我想突出显示该表的最近点击的行.我用以下Javascript做到这一点:

$('#mytable tbody tr').live('click', function(event) {
    $clicked_tr = $(this);
    $clicked_tr.parent().children().each(function() {
        $(this).removeClass('highlight')
    });
    $clicked_tr.addClass('highlight');
});
Run Code Online (Sandbox Code Playgroud)

该代码在没有条带行的表中正常工作.但是对于条带行,highlight类的背景颜色不会覆盖类的背景颜色table-striped.这是为什么?我怎样才能让它发挥作用?

iam*_*eed 79

http://jsfiddle.net/iambriansreed/xu2AH/9/

.table-striped类

.table-striped tbody tr.highlight td { background-color: red; }
Run Code Online (Sandbox Code Playgroud)

...和更清洁的jQuery:

$('#mytable tbody tr').live('click', function(event) {
    $(this).addClass('highlight').siblings().removeClass('highlight');
});?
Run Code Online (Sandbox Code Playgroud)

更新: .live()已被弃用.使用.on().

$('#mytable').on('click', 'tbody tr', function(event) {
    $(this).addClass('highlight').siblings().removeClass('highlight');
});?
Run Code Online (Sandbox Code Playgroud)

修正: http ://jsfiddle.net/iambriansreed/xu2AH/127/


Jos*_*eph 18

增加特异性.highlight

通过阅读本文并查看本答案中的演示,了解更多"CSS特异性"

//your normal green has "023"
//.table-striped  010
//tbody           001
//tr              001
//:nth-child(odd) 010 
//td              001 = 023
.table-striped tbody tr:nth-child(odd) td {
    background-color: green;
}

// your highlight only has "010"
//thus it can't take precedence over the applied style
.highlight{
    background-color: red
}

//a more specific highlight =  "033" will take precedence now
//.table-striped  010
//tbody           001       
//tr              001       everything is about the same except
//.highlight      010   <-- an added class can boost specificity
//:nth-child(odd) 010 
//td              001 = 033
.table-striped tbody tr.highlight:nth-child(odd) td {
    background-color: red;
}
Run Code Online (Sandbox Code Playgroud)


小智 5

这更容易,只需使用 de Bootstrap css 类(如 .info .warning .error 或 .success )在选定行和未选定行之间切换。他们拥有该行的所有状态。

我根据 @iambriansreed 的回答使用了这个:

$('#mytable tbody tr').live('click', function(event) {
    $(this).addClass('info').siblings().removeClass('info');
}
Run Code Online (Sandbox Code Playgroud)