2012-05-04 106 views
0

我有一個內部div中有標籤的帖子鏈接列表。用戶從三個不同的列表中選擇來過濾帖子。jQuery邏輯過濾

基本上我想實現的是基於用戶選擇的三個列表的內容進行前端過濾。

我想要的邏輯基本上是這樣的:IF post-tags-list has 1+ item from list1 AND has 1+ item from list2 AND has 1+ item from list3, THEN keep the post

下面是我作爲一個開始,但它的方式是目前我需要大量的IF語句賬戶,如果有人沒有按」 t從列表中選擇任何內容。我知道使用開關可能會更容易,但我不完全確定我的邏輯是否正確。

$(".post-link").each(function(index){ 
    //Get all the post's terms from its hidden tag div and store in an array 
    var terms = $(this).find(".tags").attr('class').split(" "); 
    //Cut off the first two items ('hidden' and 'tags') 
    terms.splice(0,2); 
    //If interests is set 
    if(typeof interests[0] != 'undefined'){ 
     var found = 0; 
     var keep = false; 
     //For each of the selected interests... 
     $.each(interests, function(index, value){ 
      //For each of the posts terms 
      $.each(terms, function(index2, value2){ 
       //If the posts has a selected interest, keep it 
       if(value == value2){ keep=true;} 
      }); 
     }); 
     //After all that, if we couldn't find anything... 
     if(keep!=true){ 
      //Hide the post (.post-link) 
      $(this).hide(); 
     } 
    } 
    //THE ABOVE ONLY ACCOUNTS FOR IF SOMETHING IS SELECTED FOR THE FIRST LIST 
    //I'M NOT SURE HOW I WOULD IMPLEMENT THIS ACROSS TWO OTHER LISTS 
}); 

如果您需要更多信息,請讓我知道。

謝謝!

回答

0

好的,所以我找到了解決我的問題的方法。基本上對於每篇文章,我設置一個show變量並將其設置爲true(除非另有證明,否則我們希望顯示帖子)。因此,我檢查我的三個列表中是否都有其中的內容,如果我這樣做,那麼在foreach中執行foreach以檢查我的一個條款是否與我選擇的項目匹配。如果存在,則保持show = true,否則其爲false。爲另外兩個列表做這個。在這三次檢查後,如果顯示仍然如此,則每個三個字段中至少有一個項目(如果三個適用),如果顯示爲false,則隱藏該帖子。

下面的代碼:

$(".post-link").each(function(index){ 
    var show = true; 

    //Get all the post's terms from its hidden tag div and store in an array 
    var terms = $(this).find(".tags").attr('class').split(" "); 
    //Cut off the first two items ('hidden' and 'tags') 
    terms.splice(0,2); 

    //If interests is set 
    if(typeof interests[0] != 'undefined'){ 
     var found = 0; 
     $.each(interests, function(index, value){ 
      $.each(terms, function(index2, value2){ 
       if(value == value2){ found++; } 
      }); 
     }); 
     if(found < 1){ 
      show = false; 
     } 
    } 

    //If type is set 
    if(typeof type[0] != 'undefined'){ 
     var found = 0; 
     $.each(type, function(index, value){ 
      $.each(terms, function(index2, value2){ 
       if(value == value2){ found++; } 
      }); 
     }); 
     if(found < 1){ 
      show = false; 
     } 
    } 

    //If experience is set 
    if(typeof experience[0] != 'undefined'){ 
     var found = 0; 
     $.each(experience, function(index, value){ 
      $.each(terms, function(index2, value2){ 
       if(value == value2){ found++; } 
      }); 
     }); 
     if(found < 1){ 
      show = false; 
     } 
    } 

    if(!show){ 
     $(this).hide(); 
    } 
});