You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jQuery高亮所有包含最大值的列?

Solution to Highlight All Columns Containing the Max Value

Great question! The problem with your existing code is that when $('th').filter(...) returns multiple <th> elements (all matching your max value), calling .index() on the entire collection only returns the index of the first element in that set. That's why only the first matching column gets the gold background.

To fix this, you just need to iterate over every matching <th> element and highlight its corresponding column individually. Here's the revised code:

// Find all table headers that contain the max value
var maxColumns = $('th').filter(function(){
    return $(this).text() == max;
});

// Loop through each matching header to highlight its column
maxColumns.each(function() {
    var colIndex = $(this).index();
    // Target every cell in the column (nth-child uses 1-based indexing)
    $("td, th").filter(":nth-child(" + (colIndex + 1) + ")").css("background-color", "gold");
});

Key Changes Explained:

  • Instead of storing the filtered headers in a variable and grabbing just the first index, we use .each() to loop through every matching <th> element.
  • For each header, we get its unique column index and apply the background color to all cells in that column.

If you want a slightly more efficient selector (to avoid filtering all td/th elements each time), you could also use:

$(this).closest('table').find(`tr > *:nth-child(${colIndex + 1})`).css("background-color", "gold");

This targets only the cells within the same table as the current header, which is better if you have multiple tables on the page.

内容的提问来源于stack exchange,提问作者Just a Sec User

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:17:31