Using the Jquery closest() function?

喜欢而已 提交于 2019-12-07 01:02:43

问题


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; 
    });
});


来源:https://stackoverflow.com/questions/1346972/using-the-jquery-closest-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!