【问题标题】:Using the Jquery closest() function?使用 Jquery 最接近()函数?
【发布时间】:2009-08-28 13:29:17
【问题描述】:

这是我的 HTML:

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

我目前有这个 JQuery 代码,

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

由于某种原因,closest() 函数不起作用,它不会切换表格行 .r3c - 我尝试使用 parent 和其他替代方法,但也无法使其正常工作:(

对于这个愚蠢的问题,以及与我之前遇到的问题类似的问题,我们深表歉意。只是想知道,最好的解决方案是什么?

谢谢!

【问题讨论】:

    标签: closest jquery


    【解决方案1】:

    closest() 查找最近的父代,而不是父母-兄弟-孩子。

    你想要这样的东西:

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

    【讨论】:

    • 因为问题是“使用 Jquery 最接近()函数?”这肯定是最好的答案。其他答案是关于如何在不使用最近的情况下使用 jquery 遍历 DOM 的问题:)
    【解决方案2】:

    尝试:

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

    【讨论】:

      【解决方案3】:

      也许这会起作用:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-29
        • 2010-11-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多