2011-01-25 172 views
1

我試圖通過兩個不同的來源切換細節行。使用2種不同的切換功能切換相同的表格行

  1. 如果用戶點擊名稱或在AddressAlert,那麼具體的詳細信息行被顯示或隱藏
  2. 如果用戶點擊「切換所有」行得到顯示或隱藏,然後所有的細節。

問題是兩個獨立的切換函數不知道另一個切換函數是什麼。因此,例如,如果點擊「切換全部」,現在顯示所有詳細信息行,單擊單個名稱應該隱藏該詳細信息行。但是,由於單個切換功能可達「顯示」,因此需要2次點擊才能隱藏該行的詳細信息。

的HTML:

<div id="toggleAll"></div> 
<table> 
    <tr class="infoRow"><td class="addressAlert"></td><td class="name"></td></tr> 
    <tr class="details"></tr> 
    <tr class="infoRow"><td class="addressAlert"></td><td class="name"></td></tr> 
    <tr class="details"></tr> 
    <tr class="infoRow"><td class="addressAlert"></td><td class="name"></td></tr> 
    <tr class="details"></tr> 
</table> 

的JavaScript:

//toggles beween showing and hiding the details for specific row 
$(
    function(){ 
     //if click on carrier name or address alert symbol 
     $('.name, .addressAlert').toggle(
      function() { 
      //gets the row clicked on, and finds the next row (the details row) 
      detailsTds = $(this).parents("tr.infoRow").next(); 
      //adds the "shown" class, which sets the display to table-row 
      detailsTds.addClass("shown"); 
      }, 
      function(){ 
      //gets the row clicked on, and finds the next row (the details row) 
      detailsTds = $(this).parents("tr.infoRow").next(); 
      //removes the "shown" class, thereby setting the display to none 
      detailsTds.removeClass("shown"); 
      } 
     ); 
    } 
); 

//toggle ALL details 
$(
    function(){ 
     //if click on carrier name or address alert symbol 
     $('#toggleAll').toggle(
      function() { 
      $('.details').addClass("shown"); 
      $('#toggleAll').text('[-] Hide all addresses'); 
      }, 
      function(){ 
      $('.details').removeClass("shown"); 
      $('#toggleAll').text('[+] Show all addresses'); 
      } 
     ); 
    } 
); 
+0

它值得在jQuery上toggleClass函數也值得熟悉。它不會直接幫助您切換相同的東西,但可以讓您在沒有兩個接近相同的函數的情況下編寫更乾淨的代碼(因爲它們通常與添加/刪除類調用不同)。 – Chris 2011-01-25 16:54:23

回答

2

你可以使用點擊()而不是切換(),然後顯示或基於當前應用於類隱藏行。

0

你能直接引用這個類嗎?

+0

我不明白你的意思... – dmr 2011-01-25 16:15:03

0

你爲什麼不更換第一個切換功能: 「$(‘名稱,.addressAlert。’)進行切換。」

,然後用所示講座 所以先初始化所有infoRows時間它會被顯示,即使用戶按下「切換全部」