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

如何在第一个td值为'test'时禁用表格中其他td元素?

问题

希望当表格中某一行的第一个<td>内容为'test'时,禁用该行的第二个或第三个<td>内的输入控件。示例表格结构如下:

<table id="ctl00_PlaceHolderMain_subElems7909_repSubElems_tblData">
  <tr>
    <td >John</td>
    <td ><input type="text"  name="lname" ></td>
    <td >Blah</td>
  </tr>
  <tr>
    <td >Test</td>
    <td ><input type="text"  name="lname" ></td>
    <td >Blah</td>
  </tr>
</table>

尝试了以下jQuery代码但未生效:

$("#ctl00_PlaceHolderMain_subElems7909_repSubElems_tblData tr").each( function( index, val ){
    if($(this).find("td:first-child").text() == 'Test;') {
        $(this).find("td:last-child").prop('disabled',true);
    }
});

使用hide()方法可以正常生效,但使用禁用方法无效,想知道原因。

原因与解决方法
  • 核心原因:disabled属性仅对表单控件(如<input>、<select>、<button>等)生效,你当前是给<td>表格单元格设置该属性,而<td>本身不支持disabled,所以设置后没有任何效果。而hide()是jQuery通用的DOM元素隐藏方法,对所有元素都适用,因此能正常工作。
  • 额外逻辑问题:你的判断条件写的是'Test;'(带分号),但表格中目标行的内容是'Test'(无分号),这会导致判断逻辑根本不会触发,即使后续代码正确也无法执行。

正确的实现代码应该是定位到<td>内的表单控件,再给控件设置disabled属性:

$("#ctl00_PlaceHolderMain_subElems7909_repSubElems_tblData tr").each(function() {
    // 修正判断文本,添加trim()避免空格干扰判断
    if ($(this).find("td:first-child").text().trim() === 'Test') {
        // 禁用第二个td内的input
        $(this).find("td:nth-child(2) input").prop('disabled', true);
        // 如果需要禁用第三个td内的控件(若存在),可添加此行
        // $(this).find("td:nth-child(3) input").prop('disabled', true);
    }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 00:37:25