简体   繁体   中英

Change background color of a datatable <tr>

I am trying to change background of a <tr> of a datatable which is like this.

var lastIdx = null;
var t = $("#campaigns_list").DataTable();

t.rows.add(['.$str_json.']).draw();

$("#campaigns_list tr").not(":first").hover(
  function() {
    $(this).css("background", "yellow");
  },
  function() {
    alert("bye");
  }
);

But I don't know why, the background-color of the <tr> isn't changing.

$(this).css("background","yellow");

This code seems to be unable to change color. However, the hover function do call itself, cause if I am replacing the above line with an alert then the alert is happening fine.

It's most likely the <td> inside your <tr> that needs to have the background color instead.

EDIT: For example:

$(this).find('td').css('background', 'yellow');

Seems to me this is an issue of event delegation, as this is used with datatables . Datatables plugin generates the trs dynamically and you are binding the event on page load and trs are getting generated after DOM has been loaded, so you can try with delegating the event to the closest static parent or document itself:

$("#campaigns_list").on('hover mouseenter', 'tr:not(:first)', function(){

or you can event try with this too:

$(document).on('hover mouseenter', '#campaigns_list tr:not(:first)', function(){

you can delegate to the closest static parent or to the $(document) itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM