jQuery点击月份表头仅高亮对应下方列的问题求助
Let's sort out this issue—your current jQuery is highlighting the entire row below the month header, but we need to target only the 12 columns that belong to the clicked month. Here's how to adjust your code:
First, understand the problem with your existing code
Your loop is redundant (you don't need to loop 12 times to bind the click event to all .month_header elements), and $(this).parent().next('tr') selects the entire row, not just the columns linked to the clicked month.
Solution 1: Direct CSS manipulation
Replace your jQuery code with this:
$(document).ready(function () { $('.month_header').on('click', function () { // Clear any existing highlights first $('.header_column_group th').css('background', ''); // Get the index of the clicked month (starts at 0 for January) const monthIndex = $('.month_header').index(this); // Calculate the range of columns for this month (12 columns per month) const startCol = monthIndex * 12; const endCol = startCol + 11; // Target only the columns in this range and set their background $('.header_column_group th').slice(startCol, endCol + 1).css('background', 'red'); }); });
Solution 2: Use CSS classes (better practice)
For cleaner separation of style and behavior, define a CSS class instead of setting styles directly in JS:
.month-column-highlight { background-color: red; }
Then update your jQuery to use this class:
$(document).ready(function () { $('.month_header').on('click', function () { // Remove highlight from all columns first $('.header_column_group th').removeClass('month-column-highlight'); const monthIndex = $('.month_header').index(this); const startCol = monthIndex * 12; const endCol = startCol + 11; // Add the highlight class to the target columns $('.header_column_group th').slice(startCol, endCol + 1).addClass('month-column-highlight'); }); });
How this works:
$('.month_header').index(this)tells us which month was clicked (0 = January, 1 = February, ..., 11 = December).- Since each month maps to 12 columns, we calculate the start and end positions of those columns in the header row.
slice(startCol, endCol + 1)selects exactly those 12 columns (jQuery'ssliceis left-inclusive, right-exclusive, so we add 1 to include the last column).
This way, clicking a month header will only highlight its corresponding 12 data columns, not the entire row.
内容的提问来源于stack exchange,提问作者Dan Angelo Alcanar

