首页 > 解决方案 > 条纹表的选定行颜色

问题描述

我希望表格的选定行具有某种背景颜色。我的桌子是条纹的,它只适用于白色行。我正在使用 datatables.net。

如果选择灰色行,我希望灰色行的颜色相同,然后选择白色行。但是使用此代码,它会通过单击将白色行变为灰色。但是,如果我只使用第一个 if else 块,它适用于白色行。我究竟做错了什么?

if (this.style.background == 'white') {
  $(this).css('background', '#cce6ff');
} else {
  $(this).css('background', 'white');
}

if (this.style.background == 'lightgrey' && this.style.background != 'white') {
  $(this).css('background', '#cce6ff');
} else if (this.style.background != 'white') {
  $(this).css('background', 'lightgrey');
}

这也不起作用:

  if (this.style.background == 'white'){
        $(this).css('background', '#b6c7db');
        break;
    }else{
        $(this).css('background', 'white');
        break;
    }
    if (this.style.background == 'lightgrey' && this.style.background != 'white'){
        $(this).css('background', '#cce6ff');

    }else if (this.style.background != 'white'){
        $(this).css('background', 'lightgrey');}

标签: javascriptjquerycssmodel-view-controllerdatatable

解决方案


您需要确保this实际上是指该行。如果没有,您将需要调整它以定位该行。

也就是说,假设数据表已经将选定的类添加到行中,您可以使用 CSS 来定位它。

然后,如果上述方法仍然不起作用,则很可能您需要使用!important来强制该值,这无疑会在其他地方被覆盖

方法 2:您应该使用您拥有的 CSS 规则来执行此操作,并避免检查当前颜色。在选择时,从所有行中删除selected类并在被选择的行上切换它。

您的代码是否在点击处理程序中?您的第二个片段中有break语句,此代码是否在循环中?我觉得你对条件语句有一些误解,但我很难理解那些代码片段试图实现的目标——例如,this.style.background == 'lightgrey' && this.style.background != 'white'不必要的冗长,如果背景等于lightgrey,那么它不会等于white,第二次比较可以删除。


推荐阅读