如何在第一个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
相关产品推荐
相关产品推荐

