我有这个HTML代码:

<tr>
  <td><input type="checkbox" class="chk" /></td>
  <td><div class="disabled">text to hide 1</div></td>
  <td><div class="disabled">text to hide 2</div></td>
</tr>

我正在使用jQuery隐藏所有class="disabled"项:
$("div.disabled").hide() ;

当我单击同一行(tr)中的复选框时,我想显示禁用的div。
我试过了
$("input.chk").click(function(){
  $(this).parent().parent().(".disabled").show();
}) ;

但这不起作用。

最佳答案

使用 .closest() .find() ,如下所示:

$("input.chk").click(function(){
  $(this).closest('tr').find(".disabled").show();
});

您当前的代码几乎可以用,但是您需要一个 .find() ,如下所示:
$(this).parent().parent().find(".disabled").show();

如果您有很多这样的行,请使用 .delegate() ,如下所示:
$("table").delegate("input.chk", "click", function(){
  $(this).closest('tr').find(".disabled").show();
});

.delegate() 而是将一个处理程序绑定(bind)到表,以使所有input.chk元素冒泡。如果您要启用/禁用,除了上述内容之外,还可以使用change .toggle() ,如下所示:
$("table").delegate("input.chk", "change", function(){
  $(this).closest('tr').find(".disabled").toggle(this.checked);
});

这样,如果选中,它们就会显示,否则,它们就会隐藏。

09-25 17:03
查看更多