【问题标题】:How do I find the nearest tbody then loop through its rows and hide them我如何找到最近的 tbody 然后遍历它的行并隐藏它们
【发布时间】:2013-02-21 12:48:32
【问题描述】:

我有一个分成几个 tbody 的表。每个 tbody 的第一行都有一个按钮,用于隐藏该 tbody 中的所有其他行,除了其中包含按钮的行。

不知道如何实现。

我的 HTML:

<table>
   <tbody>
       <tr>
           <td><button class="hide_button_main"> x </button></td>
           <td>Label</td>
       </tr>
        <tr>
            <td>Zone 1</td>
            <td></td>
        </tr>
        <tr>
            <td>Zone 2</td>
            <td></td>
        </tr> 
        <tr>
            <td>Zone 3</td>
            <td></td>
        </tr> 
       <tr>
            <td>Zone 4</td>
            <td></td>
        </tr> 
   </tbody>

区域 1 到 4 的行将被隐藏,但带有标签的行不会隐藏

我的 Jquery:

     $('.hide_button_main').click(function(e) {

   // var rows = $(this).closest('tbody').find('tr').length;

    var rows = $(this).closest('tbody');

        rows.each(function() {

      alert('1');

    });


});

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    你可以用这个

    $('.hide_button_main').click(function(e){
        $(this).closest('tbody').hide();
    });
    

    或者如果你想隐藏 tbody 孩子这样做

    $('.hide_button_main').click(function(e){
        $(this).closest('tbody').find('tr').hide();
    });
    

    【讨论】:

    • "...隐藏此 tbody 中除包含按钮的行之外的所有其他行。"
    • 谢谢,我已经编辑了我的评论,我的英语不够好:D
    【解决方案2】:

    这应该可行:

    $('.hide_button_main').click(function(e){
        $(this).closest('tr').siblings().hide(); // hide all except self
    });
    

    【讨论】:

      【解决方案3】:

      我认为应该这样做

      $('table').on('click', '.hide_button_main', function(e) {
          var target = $(e.currentTarget);
          var row = target.closest('tr');
          console.log('console', target, row, row.siblings())
          row.siblings().hide();
      });
      

      演示:Fiddle

      这里我们使用了使用 jQuery.on 的委托事件注册模型。如果我们有很多必须附加事件处理程序的元素,建议这样做。

      【讨论】:

        【解决方案4】:

        他想隐藏所有兄弟行,所以:

        $('.hide_button_main').click(function (e) {
           var $currentRow = $(this).closest('tr');
           var $otherRows = $currentRow.siblings();
           $otherRows.hide();
        });
        

        演示:http://jsfiddle.net/NeXMh/1/

        编辑

        处理多个表时,使用单个事件处理程序:

        $('table').on(click, '.hide_button_main', (function (e) {
           var $currentRow = $(this).closest('tr');
           var $otherRows = $currentRow.siblings();
           $otherRows.hide();
        });
        

        【讨论】:

          【解决方案5】:

          隐藏除第一行以外的所有行...

            $('.hide_button_main').click(function(e){
                  $(this).closest('tbody').find('tr:not(:first)').hide();
              });
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-04-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多