2013-02-21 17 views
0

我有一張分成幾個tbody的表。每個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'); 

    }); 


}); 

回答

1

您可以使用此

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

或者,如果你想隱藏的tbody孩子做這樣的

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

「...將此行中的所有其他行與其中的按鈕隱藏在此行之外。 「 – iappwebdev 2013-02-21 12:55:43

+0

謝謝,我編輯了我的評論,我的英文不夠好:D – nvl 2013-02-21 13:02:04

0

這應該工作:

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

我想這應該這樣做

$('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使用委託事件註冊模型。如果我們有很多要附加事件處理函數的元素,那麼推薦使用它。

0

他想隱藏所有的兄弟姐妹行,所以:

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

DEMO:http://jsfiddle.net/NeXMh/1/

編輯

當幾個表的工作,然後用單事件處理工作:

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

隱藏除第一個以外的所有行...

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