2012-02-03 50 views
1

我有一個列表,當選擇一個鏈接時,div的關聯將隱藏。jQuery,使用鏈接和數據選擇器過濾列表

首先,是否有更簡單的方法來編寫代碼以使選擇器查找與按鈕關聯的數據?

其次,當選擇多個鏈接並且再次點擊一個鏈接時,該鏈接會回到默認狀態。有沒有解決這個問題?

$(document).ready(function() { 

     $('#show-free').click(function() { 

      if ($('#show-free').hasClass('active')) { 
       $('.book[data-price!="0"]').trigger('show') 
       $(this).removeClass('active'); 

      } else { 
       $('.book[data-price!="0"]').trigger('hide'); 
       $(this).addClass('active'); 
      } 
     }); 

     $('#show-paid').click(function() { 

      if ($('#show-paid').hasClass('active')) { 
       $('.book[data-price="0"]').trigger('show') 
       $(this).removeClass('active'); 
      } else { 
       $('.book[data-price="0"]').trigger('hide'); 
       $(this).addClass('active'); 
      } 
     }); 

     $('#show-new').click(function() { 

      if ($('#show-new').hasClass('active')) { 
       $('.book[data-weeks-on-list="0"]').trigger('show') 
       $(this).removeClass('active'); 
      } else { 
       $('.book[data-weeks-on-list="0"]').trigger('hide') 
       $(this).addClass('active'); 
      } 
     }); 


     $('#show-old').click(function() { 

      if ($('#show-old').hasClass('active')) { 
       $('.book[data-weeks-on-list!="0"]').trigger('show') 
       $(this).removeClass('active'); 
      } else { 
       $('.book[data-weeks-on-list!="0"]').trigger('hide') 
       $(this).addClass('active'); 
      } 
     }); 


     $('.book').on('show', function() { 
      $(this).show('slow'); 
     }).on('hide', function() { 
      $(this).hide('slow'); 
     }) 


    }); 

回答

0

爲了便於找到與鏈接相關的使用數據的數據()jQuery的方法也許

$('.book').filter(function(obj){ 
    return obj.data('price') != '0'; 
} 

代替

$('.book[data-price!="0"]') 

實際上是更好 - 我懷疑不行。這只是一個選擇。

隨着點擊功能 - 因爲你沒有在方法中返回false,那麼鏈接的默認行爲將被觸發,我想會導致鏈接重置。我會嘗試在點擊內返回false來抑制這種行爲。

這有幫助嗎?