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

基于TD单元格值设置背景色:避免文本片段匹配冲突

解决TD单元格精确匹配文本设置背景色的问题

问题根源

你当前使用的:contains选择器是模糊匹配,只要单元格文本包含指定字符串片段就会被选中。加上代码执行顺序的影响,比如Lion Intensive会先被匹配Lion Intensive的代码设为红色,随后又被匹配Intensive的代码覆盖为白色,最终导致包含相同片段的单元格颜色一致。

解决方案

改用jQuery的filter()方法,对每个<td>的文本内容做精确匹配,同时用$.trim()处理文本前后的空格,避免因空格导致匹配失败:

// 精确匹配"M/S Select Farm"
$('td').filter(function() {
  return $.trim($(this).text()) === "M/S Select Farm";
}).css('background', 'yellow');

// 精确匹配"Lion Free Range"
$('td').filter(function() {
  return $.trim($(this).text()) === "Lion Free Range";
}).css('background', 'blue');

// 精确匹配"Barn"
$('td').filter(function() {
  return $.trim($(this).text()) === "Barn";
}).css('background', 'orange');

// 精确匹配"Free Range"
$('td').filter(function() {
  return $.trim($(this).text()) === "Free Range";
}).css('background', 'green');

// 精确匹配"Lion Intensive"
$('td').filter(function() {
  return $.trim($(this).text()) === "Lion Intensive";
}).css('background', 'red');

// 精确匹配"Intensive"
$('td').filter(function() {
  return $.trim($(this).text()) === "Intensive";
}).css('background', 'white');

补充说明

这种方式下,每个单元格只会被完全匹配的规则选中,不会再出现因包含相同文本片段而被错误设置样式的问题,代码执行顺序也不再影响最终结果。

内容的提问来源于stack exchange,提问作者Stuart Bird

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 04:35:40