1

下面的功能允许用户通过 过滤产品data-attributes,并支持同时按多个值过滤。如何on load在每个选项旁边显示潜在结果的数量?理想情况下,我还想显示他们运行的每个搜索的结果总数。

我在这里发布了一个函数的工作示例:http: //jsfiddle.net/chayacooper/hSwcr/1/

    var selected = { color: [], style: [] };   
    $('.filterOptions').on("change", ":checkbox", function (e) {
        var type = $(e.delegateTarget).data("type");
        var $this = $(this);
        var attrValue = $this.data(type);
        if ($this.parent().hasClass("active")) {
            $this.parent().removeClass("active");
            selected[type].splice(selected[type].indexOf(attrValue),1);
        }
        else {
            $this.parent().addClass("active");
            selected[type].push(attrValue);
        }            
        var checked = $(":checked", ".filterOptions");            
        // show all of the available options if...
        if (checked.length == 0 || checked.filter(".all").length > 0) {
            $('#content').find('*').show();
        } 
        else {
            $("#content").find("*").hide();
            for (var key in selected) {
                $.each(selected[key], function(index,item) {
                    $('#content').find('[data-' + key + ' *="' + item + '"]').show();
                });
            }
        }
    }); 
4

1 回答 1

1

根据您当前的实现,您可以在复选框更改事件处理程序中的“for in”循环中执行此操作:

for (var key in selected) {
            $.each(selected[key], function(index,item) {
                var $products = $('#content').find('[data-' + key + ' *="' + item + '"]'),
                    totalCount = $products.length;

                $.each($products, function(idx, product){
                      //implement logic for running count for product options                    
                });

                //implement logic to append count to options and display totalCount


                $products.show();
            });
        }

但是,我建议您退后一步,为您的所有具有属性和属性值的产品创建一个 JS 对象文字,以便您可以将数据与 UI 分开。对于您的数据,您可以使用 underscore.js 之类的库来查询您的数据以获取总结果、过滤产品并计算每个选项的潜在总数。对于您的 UI (HTML),您可以使用 mustache.js、handlebars.js、knockout.js 等模板框架来绑定您的查询数据。恕我直言,这将使您的生活更轻松。

示例 JS 对象:

{ products: [
    {
        product: "Sleeveless, V-Neck, Black, Red", 
        attributes : [
         {
               attributeName: "color",
               attributeValue: "Red"
         },
         {
               attributeName: "color",
               attributeValue: "Black"
         },
         {
               attributeName: "style",
               attributeValue: "V-Neck"
         },
         {
               attributeName: "style",
               attributeValue: "Sleeveless"
         }
      ]
  },

  //etc.....

  ]
}  
于 2013-04-16T06:53:22.490 回答