2013-03-23 64 views
0

我试图合并几个find函数,以便通过多个数据属性过滤项目。我希望它返回匹配任何过滤器的所有项目,并在其中一个过滤器被删除时恢复到其他过滤器的更严格标准(我将在后面添加排名算法 - 可能是QuickSilver,但仍然可以找出出 - 为了显示更强的匹配第一)将几个find()函数组合起来以显示匹配所有指定过滤器的结果

我不确定如何正确合并不同的find函数,以便它们能够正确地一起工作。目前,过滤器一次只能工作一次(以最后一次触发为准)。我已经发布了小提琴这里的功能的一个简单的例子:http://jsfiddle.net/chayacooper/WZpMh/13/


更新 - @Sergei Gorjunov的解决方案是几乎没有,我只是需要一些帮助修改它使用或代替,并且使得它会显示与任一过滤器匹配的产品(将&&替换为||使功能停止工作)。

我也改性的大部分代码,使得它不需要指定所述标签元件(即<li><td>,并相应地更新的小提琴。

$(document).ready(function() { 
    $('#attributes-Colors *').click(function() { 
     var attrColor = $(this).data('color'); 
     $('#attributes-Colors').removeClass('active'); 
     $(this).parent().addClass('active'); 
     if (attrColor == 'All') { 
      $('#content').find('*').show(); 
     } else { 
      $('#content').find('li:not([data-color="' + attrColor + '"])').hide(); 
      $('#content').find('td:not([data-color="' + attrColor + '"])').hide(); 
      $('#content').find('[data-color ~="' + attrColor + '"]').show(); 
     } 
     return false; 
    }); 

    $('#attributes-Silhouettes *').click(function() { 
     var attrStyle = $(this).data('style'); 
     $('#attributes-Silhouettes').removeClass('active'); 
     $(this).parent().addClass('active'); 
     if (attrStyle == 'All') { 
      $('#content').find('*').show(); 
     } else { 
      $('#content').find('li:not([data-style="' + attrStyle + '"])').hide(); 
      $('#content').find('td:not([data-style="' + attrStyle + '"])').hide(); 
      $('#content').find('[data-style ~="' + attrStyle + '"]').show(); 
     } 
     return false; 
    }); 
}); 

回答

1

我已经找到了如何过滤这些项目的方法。

$.fn.extend({ 
    filterMyItems: function() { 
     function filterItems() {    
      var color = $('#filterColorOptions').find('li.active a').data('color'), 
       style = $('#filterStyleOptions').find('li.active a').data('style'); 

      if (color == "All") color = ".+"; 
      if (style == "All") style = ".+"; 

      var colorPattern = new RegExp(color, 'i'), 
       stylePattern = new RegExp(style, 'i'); 

      return (colorPattern.test($(this).data('color')) && stylePattern.test($(this).data('style'))); 
     } 

     $(this).filter(filterItems).show(); 
     $(this).not(filterItems).hide(); 
    } 
}); 

$(document).ready(function() { 
    $('.filterOptions a').click(function(e){ 
     e.preventDefault(); 
     $(this).closest('.filterOptions').find('.active').removeClass('active'); 
     $(this).parent().addClass('active'); 
     $('#content li').filterMyItems(); 
    });  
}); 

链接的jsfiddle:http://jsfiddle.net/WZpMh/7/

+0

这就是我一直在寻找:-D我怎么会返回结果匹配“风格”或“颜色”(替换“&&”与||所做的功能停止工作,所以显然不是这样;-))。另外,你介意解释一下代码,以便我知道如何使用它(例如,将其更改为使用复选框以允许用户为每个数据属性选择多个值)? – 2013-03-23 17:08:16

+0

它可以工作,如果你把||代替 &&。但是,如果您只选择红色,它的含义是“给我所有红色物品或带有样式属性的所有物品”。在这种情况下,我们可以在过滤条件中做一些条件,如if(style ==“All”&& color!=“All”)style =“”;'。 关于解释 - 我可以为你解释,但更好的做法是在Facebook或Skype上做。 – 2013-03-23 23:10:20

+0

我认为它可以工作,但函数只是停止工作:-(除了'&&'之外还有其他我需要更改的东西吗? – 2013-03-24 16:46:28

相关问题