2014-05-02 53 views
0

我使用的分類filteritemsselectors的數據屬性product-collection__category完全匹配。但我只想要一個部分或懶惰的匹配。例如,如果selector包含「貓」,它將仍然包括具有「貓」,「類別」等的items。我試過if (categories[i] *= cat),但它是錯誤的。部分匹配數據屬性

Fiddle

HTML

<div class="product-collection"> 
    <ul> 
     <li class="product-collection__selector 
        product-collection__selector--active" 
      data-product-collection__category="">All</li> 
     <li class="product-collection__selector" 
      data-product-collection__category="cat1">Category 1</li> 
     <li class="product-collection__selector" 
      data-product-collection__category="cat2">Category 2</li> 
    </ul> 
    <ul> 
     <li class="product-collection__item" 
     data-product-collection__category="cat1">Item 1 [cat 1]</li> 
     <li class="product-collection__item" 
     data-product-collection__category="cat2">Item 2 [cat 2]</li> 
     <li class="product-collection__item" 
     data-product-collection__category="cat1 cat2">Item 3 [cat 1, cat 2]</li> 
    </ul> 

</div> 

代碼

$(function() { 
$('.product-collection').each(function() { 
     var $collection = $(this); 
     var $selectors = $collection.find('.product-collection__selector,.filterselect__selector'); 
     var $items  = $collection.find('.product-collection__item'); 

     $selectors.click(function() { 
      var $selector = $(this); 
      var cat = $selector.data('product-collection__category'); 


     $selectors.change(function() { 
     var $selector = $(this); 
     var cat = $selector.find('option:selected').data('product-collection__category'); 

     $selectors.removeClass('filterselect__selector--active'); 
     $selector.addClass('filterselect__selector--active'); });     

      if (cat) { 
       var containsCategory = function(data) { 
        var categories = data.split(/\s+/); 
        for (var i = 0; i < categories.length; i++) 
         if (categories[i] == cat) 
          return true; 
        return false; 
       }; 
      } 
      else { 
       $items.fadeIn(); 
      } 
     }); 
    }); 
}); 
+0

你可以添加標記或設置一個小提琴,讓你的問題更清楚嗎? –

+0

@JayBlanchard,嗨,我已經設置了一個小提琴並添加html標記的帖子 – RedGiant

回答

1

我簡化了小提琴,這樣你可以看到活動的選擇和測試 - http://jsfiddle.net/cYFLe/64/

$('li').each(function() { 
    // test the data attribute for partial 
    if($(this).is('[data-product-collection__category*="cat"]')) { 
     console.log($(this).text()); 
    } 
}); 

http://api.jquery.com/is/是這裏的區別,它允許對真實類別進行測試。