2015-10-16 60 views
0

我試圖建立一個簡單的窄過濾器使用給定的關鍵字按鈕上的其他靜態項目的列表。需要JQuery或JavaScript來使用.contains()with &&邏輯

這些按鈕位於無序列表中,選中時會將類添加到「.selected-tag-button」中。

這些項目是div類與「.item」類和獲得類「.included-item」,當他們是活躍的。 div內是另一個UL列表項,其中包含與按鈕上的文本節點相匹配的關鍵字。

現在它正在工作,除了使用「buttonName」僅包含點擊按鍵的關鍵字,我想使用「buttonArray」,其中包含所有選定關鍵字的數組。

我想我會需要某種功能,但我不知道從哪裏開始。如果選擇了多個選項,我希望結果僅限於包含所有選定關鍵字的項目。我所能找到的所有解決方案都將返回包含數組中任何關鍵字的div。

$(document).ready(function() { 

    $("li.tag-button").on("click", function() { 

    // Toggle button 
    $(this).toggleClass("selected-tag-button"); 

    // Remove included-item class from all items 
    $(".item").removeClass("included-item"); 

    // Pass the button text into variable 
    var buttonName = $(this).text().slice(2); 

    // Create array with button text for all active buttons 
    var buttonArray = $(".selected-tag-button").map(function() { 
     return $(this).text().slice(2); 
    }).get(); 
    console.log(buttonArray); 

    // Add included-item class to divs containing the button text 
    $('li:contains("' + buttonName + '")').parents().parents().addClass("included-item"); 

    // If all buttons are inactive, add included-item class to all items 
    if ($(".selected-tag-button").length == 0) { 
     $(".item").addClass("included-item"); 
    } 

    }); 

}); 
+0

請清除你的問題。把你的HTML代碼。 –

回答

0

考慮這個小提琴:

http://jsfiddle.net/6qavvth8/

for(i=0; i<buttonArray.length;i++){ 
    contains += ':contains("' + buttonArray[i] + '")'; 
} 
$('ul' + contains).parents().addClass("included-item");  

遍歷您的按鈕配置,以建立自己的jQuery選擇和不斷增加:包括()

+0

這與一些調整工作。必須修復i-0到i = 0,定義並清除循環外部的contains變量,以便每次單擊重新設置它,並將li更改爲ul,以便它接受包含該術語集的所有列表,而不是尋找包含它們的單個列表項目。 – talbotini

+0

哦,我的壞,關於i-0的事情,只是一個草率的錯字。我會編輯。 – bingo

0

的@賓果的解決方案稍作修改。完美的作品,謝謝。

$(document).ready(function() { 

    $("li.tag-button").on("click", function() { 

    // Toggle button 
    $(this).toggleClass("selected-tag-button"); 

    // Remove included-item class from all items 
    $(".item").removeClass("included-item"); 

    // Create array with button text for all active buttons 
    var buttonArray = $(".selected-tag-button").map(function() { 
     return $(this).text().slice(2); 
    }).get(); 

    // Add included-item class to divs containing the button text 
    var contains = ""; 
    for(i = 0; i < buttonArray.length; i++){ 
     contains += ':contains("' + buttonArray[i] + '")'; 
    } 
    $('ul' + contains).parents().addClass("included-item");  

    // If all buttons are inactive, add included-item class to all items 
    if ($(".selected-tag-button").length == 0) { 
     $(".item").addClass("included-item"); 
    } 

    }); 

});