代码之家  ›  专栏  ›  技术社区  ›  el_quick

jquery parent()(选择器)

  •  30
  • el_quick  · 技术社区  · 14 年前

    我有这个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();
    }) ;
    

    但它不起作用。

    6 回复  |  直到 7 年前
        1
  •  66
  •   James A Wilson    13 年前

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

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

    您当前的代码 几乎 工作,你需要一个 。查找() 尽管如此:

    $(this).parent().parent().find(".disabled").show();
    

    如果你有 许多的 像这样的行,使用 .delegate() ,如下所示:

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

    .delegate()。 相反,将一个处理程序绑定到表中 input.chk 要冒泡的元素。如果要启用/禁用,请使用 change .toggle() 除上述内容外,如:

    $("table").delegate("input.chk", "change", function(){
      $(this).closest('tr').find(".disabled").toggle(this.checked);
    });
    

    这样,如果勾选了,它们就会显示出来,如果没有,它们就会隐藏起来。

        2
  •  3
  •   Jeff Mercado    7 年前

    是,使用 find() closest() 绝对是正确的程序。有不同的写作风格。代码段在这里。

    $("input.chk").click(function() {
          var th = $(this);
          $(".disabled", th.parent().parent()).show();
    });
    
        3
  •  2
  •   user113716    14 年前

    几乎。你只是错过了这个词 find 表示 jQuery's .find() method .

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

    或者,稍微短一点的版本是 use .closest() .

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

    你也可以 use .parents() 尽管你想指出 the :first 匹配以防有嵌套表。

    $("input.chk").click(function(){
      $(this).parents('tr:first').find(".disabled").show();
    });
    
        4
  •  0
  •   Eric    14 年前

    其实比这更容易。

        $(".disabled").hide();
        $(".chk").click(function(){
            if($(this).is(":checked"))
            {
                $(this).siblings(".disabled").show();
            }
            else
            {
                $(this).siblings(".disabled").hide();
            }
        });
    

    我甚至添加了一些额外的功能,这样事件就不只是触发一次,而是根据复选框是否被选中进行切换。

        5
  •  0
  •   nubbel    14 年前

    更简单的是:

    $(".disabled").hide();
    $(".chk").click(function() {
        $(this).siblings(".disabled").toggle();
    });​
    

    -)

        6
  •  0
  •   nubbel    14 年前

    现在它工作了: http://jsfiddle.net/WAQBj/2/

    $(".disabled").hide();
    $(".chk").click(function() {
        $(this).closest('tr').find(".disabled").toggle();
    });​