Datatables add class to all body rows

被刻印的时光 ゝ 提交于 2021-01-27 13:31:29

问题


I'm new in Datatables and I have a table that displays just the first 10 rows by default. I'm trying to add this class to all rows, not just for the default 10 ...

var table = $("#datatable-buttons").DataTable({...})
table.rows.removeClass('selected')

and

$('tbody tr').removeClass('selected')

and

$(tables.table().body()).removeClass('selected')

but without any success :( Is it possible to add/remove the select class to all rows just by clicking a button?


回答1:


I believe the best way to add a certain class to all rows is upon initialization :

var table = $('#example').DataTable({
  createdRow: function ( row, data, index ) {
     $(row).addClass('selected')
  } 
}) 

You can add/remove a class to a row upon click by using

table.on('click', 'tbody tr', function() {
  var $row = table.row(this).nodes().to$();
  var hasClass = $row.hasClass('selected');
  if (hasClass) {
    $row.removeClass('selected')
  } else {
    $row.addClass('selected')
  }
})

You can also by code remove (or add) a class to all rows by

table.rows().every(function() {
  this.nodes().to$().removeClass('selected')
})

All examples in action here -> http://jsfiddle.net/c67q2b4x/




回答2:


To add class to all the rows

$('#datatable tbody').on( 'click', 'tr', function () {
  $('#datatable tbody tr').addClass('selected');
}

To remove class from all the rows (and select only the one you clicked)

$('#datatable tbody').on( 'click', 'tr', function () {

  // Removing all the selections
  $('#datatable tbody tr').removeClass('selected');

  // selecting the on which you clicked
  $(this).toggleClass('selected');
}


来源:https://stackoverflow.com/questions/43401299/datatables-add-class-to-all-body-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!