高亮显示条带HTML表中单击的行

Highlighting the clicked row of a striped HTML table

本文关键字:单击 HTML 显示 高亮      更新时间:2023-09-26

下面是我在jsFiddle上的一个问题示例。

我有一个表,通过在CSS中使用tr:nth-child(odd)强制使用带条纹的行,就像在Twitter Bootstrap中为table-striped类所做的那样。我想突出显示该表中最近单击的行。我使用以下Javascript来实现这一点:

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

该代码在没有条纹行的表中运行良好。但是对于条纹行,highlight类的背景颜色不会覆盖table-striped类的背景色。为什么?我该如何让它发挥作用?

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

.表条纹类

.table-striped tbody tr.highlight td { background-color: red; }

和清洁jQuery:

$('#mytable tbody tr').live('click', function(event) {
    $(this).addClass('highlight').siblings().removeClass('highlight');
});​

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

$('#mytable').on('click', 'tbody tr', function(event) {
    $(this).addClass('highlight').siblings().removeClass('highlight');
});​

已修复:http://jsfiddle.net/iambriansreed/xu2AH/127/

增加.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;
}

这要容易得多,只需使用de Bootstrap css类(如.info.warning.error或.success)即可在选定行和未选定行之间切换。他们拥有这场争吵的所有州。

我使用了这个,基于@iambriansreed的回答:

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

只需将Bootstrap .table-striped CSS类编辑为:

.table-striped tbody tr:nth-child(odd),
.table-striped tbody tr:nth-child(odd) th {
    background-color: #f9f9f9;
}
.table-striped tbody tr:nth-child(even){
    background-color: yellow;
}

删除所有您不想要的td样式。然后它就起作用了。

当您单击行时,还应应用此样式:

.selected { background-color:#2f96b4 !important; }

如果没有!important,它将无法工作。

据我所知:

$('#mytable tbody tr').live('click', function(event) {
    $clicked_tr = $(this);
    $('#mytable tbody tr').removeClass("highlight");
    $clicked_tr.addClass('highlight');
});​