【问题标题】:Change the color of the line select in datatables using jquery使用jquery更改数据表中行选择的颜色
【发布时间】:2018-05-14 10:44:25
【问题描述】:

我有一个带有线条的数据表,当我单击一行时,我想更改背景颜色:选择行中的红色,而其他行我想留下背景颜色:白色

我试试这个:

$(document).on('click', "#table_user tr:not(:first) td:first-child", function() {
var row_num = parseInt( $(this).parent().index() )+1; 
 if(row_num == $(this).closest('tr').index()+1){

          $(this).css({'background-color':'red'});
        }else{
          $(this).css({'background-color':'white'});
        }
});

但它不起作用

【问题讨论】:

  • if 条件永远为真。
  • 所有线条一开始都是白色的?

标签: jquery css datatable


【解决方案1】:

在您的情况下,if 条件将始终导致 true。您可以执行以下操作:

$(document).on('click', "#table_user tr:not(:first) td:first-child", function() {
  $(this).toggleClass("selected");
});

然后,对于 .selected 类,您可以根据偶数或奇数对其进行样式设置:

.selected:nth-child(even) {
  background-color: #fff;
}
.selected:nth-child(odd) {
  background-color: #f00;
}

【讨论】:

  • @sebastianlarsen 取决于你如何实现它。你能告诉我们minimal reproducible example吗? JSBin.com 是一个好的开始。
  • @sebastianlarsen 你能告诉我minimal reproducible example,以便我可以帮助你。使用 JSBin.com 并与我分享工作/非工作页面。
【解决方案2】:

如果您只希望这发生在除第一行之外的所有行上,这将起作用:

$("#table_user td").on('click', function() {
  var row_num = parseInt($(this).parent().index()) + 1;
  var cell_num = parseInt($(this).index()) + 1;
  if (row_num != 1) {
    if(cell_num == 1) {
        $(this).css('background-color', 'red')
  } 
  else {
        $(this).css('background-color', 'white');
  }
 }
});

【讨论】:

  • 好吧,不确定这是如何工作的,因为if (row_num == $(this).closest('tr').index() + 1) { 永远是正确的。不是吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-13
  • 1970-01-01
  • 2017-06-13
  • 2011-05-07
  • 2014-05-27
  • 1970-01-01
  • 2023-01-12
相关资源
最近更新 更多