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

如何用jQuery获取含boolean=true属性按钮的tr对应TD并设置样式

问题描述

我想要获取表格中所有包含带有boolean属性(值为true或false)按钮的tr对应的td,具体需要筛选出该属性值为true的td,但不清楚如何用jQuery实现。表格结构如下:

<table id="table">
    <thead>
    </thead>
    <tbody>
        <tr row-id="1">
            <td class="text-left">
                            <div />
            </td>
            <td class="text-left td-button">
                <button boolean="true">Button</button>
            </td>
        </tr>
        <tr row-id="2">
            <td class="text-left">
                <div />
                        </td>
            <td class="text-left td-button">
                <button boolean="false">Button</button>
            </td>
        </tr>
        <tr row-id="3">
            <td class="text-left">
                <div />
            </td>
            <td class="text-left td-button">
                <button boolean="true">Button</button>
            </td>
        </tr>
    </tbody>
</table>

我尝试了如下代码,但因缺乏jQuery经验无法继续推进:

function colour() {
    $("#table tbody tr").each(function() {
        let colour = $(this).children("td")[1];     
    }
}

请问如何用jQuery获取row-id为1和3的td并为其设置样式?

解决方案

别担心,我来帮你梳理清楚怎么实现这个需求~其实不用手动遍历每一行,jQuery的选择器可以直接帮我们定位到目标元素,而且代码会更简洁。

方法一:直接通过属性选择器定位

我们可以直接找到所有包含boolean="true"按钮的td,然后给它们设置样式:

function colour() {
    // 找到所有td里包含boolean属性为true的按钮的td元素
    $("#table tbody td.td-button:has(button[boolean='true'])").css("background-color", "yellow");
}

解释一下这段代码:

  • #table tbody td.td-button:先定位到表格tbody里所有带有td-button类的td(也就是包含按钮的那列)
  • :has(button[boolean='true']):筛选出里面包含boolean属性值为true的按钮的td
  • .css("background-color", "yellow"):给这些td设置背景色(你可以换成自己需要的样式)

方法二:延续你原来的遍历思路

如果你想继续用自己写的遍历行的逻辑,也可以这样修改:

function colour() {
    $("#table tbody tr").each(function() {
        // 获取当前行里的按钮元素
        const button = $(this).find("button");
        // 判断按钮的boolean属性是否为true(注意是字符串"true")
        if (button.attr("boolean") === "true") {
            // 获取当前行的第二个td(用.eq(1)返回jQuery对象,才能调用css方法)
            $(this).children("td").eq(1).css("background-color", "yellow");
            // 如果想给当前行所有td设置样式,就改成$(this).children("td").css(...)
        }
    });
}

这里要注意:原生DOM元素不能直接调用jQuery的.css()方法,所以用.eq(1)代替[1],它会返回jQuery包装后的对象。

最后记得在页面加载完成后调用这个函数:

$(document).ready(function() {
    colour();
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 17:10:48