Using the Jquery closest() function?

2019-04-26 15:22发布

问题:

Here's my HTML:

<tr>
    <td class="show_r3c">click here</td>
</tr>
<tr class="r3c">
    <td>This is what I'd like to display</td>
</tr>

And I have currently got this JQuery code,

    $(document).ready(function(){
        $(".r3c").hide();        
        $('.show_r3c').click(function() { 
                         $(this).closest('.r3c').toggle(); 
                         return false; 
        });
   });

For some reason the closest() function isn't working, and it won't toggle the table row .r3c - I've tried using parent and other alternatives but can't get it working either :(

Apologies for the silly question, and something similar to a problem I've had before. Just wondering, What's the best solution for this ?

Thanks!

回答1:

Try with:

$('.show_r3c').click(function() {
  $(this).parent('tr').next('tr.r3c').toggle();
  return false;
});


回答2:

closest() finds the closest parent not the parents-siblings-children.

You want something like:

$(document).ready(function(){
    $(".r3c").hide();

    $('.show_r3c').click(function() { 
        $(this).closest('table').find("tr.r3c").toggle(); return false; 
    });
});


回答3:

perhaps this would work:

$(document).ready(function(){
    $(".r3c").hide();

    $('.show_r3c').click(function() { 
        $(this).parent().siblings(":first").toggle(); 
        return false; 
    });
});