如何为.info表格Amount列中空值的td元素设置红色背景?
解决方法
你的HTML结构里,目标数据表格是嵌套在.info表格的<td>内的子表格,要实现仅针对Amount列的空白单元格设置背景色,需要精准定位目标列,修改后的代码及说明如下:
修改后的jQuery代码
$(document).ready(colorMissingPayment); function colorMissingPayment() { // 定位到嵌套的目标数据表格 const targetTable = $(".info table table"); // 获取Amount表头对应的列索引(从0开始计数) const amountColumnIndex = targetTable.find("th:contains('Amount')").index(); // 遍历目标表格中除表头外的指定列td targetTable.find("tr:gt(0)").each(function() { const $td = $(this).find("td").eq(amountColumnIndex); const value = $.trim($td.text()); // 判断是否为空白内容(含空格、换行等多种空白格式) if (value === "") { $td.css("background-color", "red"); } }); }
关键细节说明
- 精准定位表格:用
$(".info table table")直接选中内层的目标数据表格,避免外层表格的干扰。 - 锁定目标列:通过
th:contains('Amount')匹配表头,再用index()获取它的列位置,确保只操作该列的单元格。 - 优化空白判断:使用
$.trim()去除文本前后的空白字符,能识别单个空格、多个空格、换行等多种空白情况,比直接判断" "更可靠。 - 跳过表头行:
tr:gt(0)表示跳过索引为0的表头行,只处理数据行。
简洁版写法
如果不需要保留单独函数,也可以用链式调用简化代码:
$(document).ready(function() { const amountColIdx = $(".info table table th:contains('Amount')").index(); $(".info table table tr:gt(0) td").filter(function() { return $(this).index() === amountColIdx && $.trim($(this).text()) === ""; }).css("background-color", "red"); });
内容的提问来源于stack exchange,提问作者CutePoison
相关产品推荐
相关产品推荐

