开发者

jQuery parent().("selector")

开发者 https://www.devze.com 2023-01-18 12:11 出处:网络
I have this HTML code: <tr> <td><input type=\"checkb开发者_如何学Cox\" class=\"chk\" /></td>

I have this HTML code:

<tr>
  <td><input type="checkb开发者_如何学Cox" class="chk" /></td>
  <td><div class="disabled">text to hide 1</div></td>
  <td><div class="disabled">text to hide 2</div></td>
</tr>

I'm using jQuery to hide all class="disabled" items:

$("div.disabled").hide() ;

I want to show disabled divs when I click the checkbox in the same row (tr). I tried

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

but it doesn't work.


Use .closest() and .find(), like this:

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

Your current code almost works, you need a .find() though, like this:

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

If you have many rows like this, use .delegate(), like this:

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

.delegate() instead binds one handler to the table for all of the input.chk elements to bubble up to. If you're looking to enable/disable, use change and .toggle() in addition to the above, like this:

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

This way if it's checked they show, if not they hide.


Yes using find() and closest() is definitely the right procedure. There is a different style of writing the same. The code snippet is here.

$("input.chk").click(function() {
      var th = $(this);
      $(".disabled", th.parent().parent()).show();
});


Almost. You're just missing the word find to indicate jQuery's .find() method.

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

Or, a little shorter version is to use .closest().

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

You could also use .parents(), though you would want to indicate the :first match in case you have nested tables.

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


Its actually even easier than that.

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

I even added some extra functionality so that the event didn't just trigger once, but rather toggles based on whether the check box is checked or not.


And it's even easier:

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

:-)


Now it works: http://jsfiddle.net/WAQBj/2/

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

精彩评论

暂无评论...
验证码 换一张
取 消