使用JQuery将附加行中某些单元格的背景颜色更改为表

我在一张桌子上附加一行。 如何更改一组单元格中该行的背景颜色。 Say列有25列; 从17到22开始的列需要背景颜色更改。

这是我到目前为止所尝试的:

$("#table1").append(row1); $(row1).children('td') .not('td:eq(0)') .not('td:eq(0)') .css({ "background-color": workcolor }); 

在这里,我使用Childeren’td’,其中所有行中的细胞都变色,而我需要根据列的ID更改特定的细胞背景。

我添加了我的Html代码你可以澄清一下:

 
Image Employee 00:00 01:00 02:00 03:00 04:00 05:00 06:00 07:00 08:00 09:00 10:00 11:00 12:00 13:00 14:00 15:00 16:00 17:00 18:00 19:00 20:00 21:00 22:00 23:00

你可以这样试试:

 /* added this loop to append tr you can ignore this loop as this only for demo */ for(i=0; i<=10; i++){ var row = $(''); for(j=0; j<=25; j++){ row.append(''+j+''); } $("#table1 tbody#body1").append(row); } // demo code ends here // actual logic starts here var startIndex = $('#table1 thead th').index($('#table1 thead th[id=17]')) // get the index of id 17 var endingIndex = $('#table1 thead th').index($('#table1 thead th[id=22]')) // get the index of id 22 // iterates through all rows. $.each($('#table1 #body1 tr'), function(i, item) { // update background-color of td between the index values 17 and 22 $(item).children('td:lt('+(endingIndex + 1)+'):gt('+(startIndex - 1)+')').addClass('highlight') }); 
 .highlight{background-color: yellow;} 
  
Image Employee 00:00 01:00 02:00 03:00 04:00 05:00 06:00 07:00 08:00 09:00 10:00 11:00 12:00 13:00 14:00 15:00 16:00 17:00 18:00 19:00 20:00 21:00 22:00 23:00

你可以尝试.filter()

 $(row1).find('td').filter(function(index){ return parseInt(this.id) >= 17 && parseInt(this.id) <= 22 }).css({ "background-color": yellow}); 

上面的例子使用td id this.id你可以使用index传递filter函数来改变它,如果你使用td索引

你仍然可以在filter()之前使用.css()为行设置所有td

 $(row1).find('td').css({ "background-color": workcolor }).filter(function(){ return parseInt(this.id) >= 17 && parseInt(this.id) <= 22 }).css({ "background-color": yellow}); 

笔记:

  • 如果你正在寻找行id而不是td id,则无需使用.find('td')
  • 如果你想用td引用行,你可以继续使用.find('td') ,在filter上你可以使用parseInt($(this).closest('tr').attr('id'))

直到你的问题更新 ..你可以使用css来做到这一点

 th:nth-child(n + 20):not(:nth-child(26)), td:nth-child(n + 20):not(:nth-child(26)){ background : yellow; } 

说明:

为什么(n + 20) ? 因为nth-child索引从1开始。所以如果你计算id为17的元素,你会发现它的索引是20,而n + 20将选择索引为20及以上的元素,并且:not(:nth-child(26))不是最后一栏

您可以使用gt和lt选择器的组合:

 $("#table1").append(row1); $(row1).children('td:gt(17):lt(22)').css('background-color', workcolor);