基於JSON+JQuery實現的多條件篩選功能(類似京東和淘寶功能)


首先看一下實現效果:


現在JSON用於數據的封裝和管理越來越流行,一直想着通過JSON實現很多的小工具,比如多條件篩選、表格定製化、數據驗證、tree樹等等,最近沒事就用JSON和JQuery實現了類似於京東和淘寶多條件篩選功能,下面會對代碼進行解釋,並有對應的demo提供給大家。

<div id="filter">   

</div>  
<script>
//加載事件  
var data=[

"url":"",
"title": "品牌",
"name":"pinpai",
"multiple": true,
"data": [ 

"id":"-1",
"css":"common",
"name":"all",
"value": "全部"
},
{
"id":"1",
"css":"common",
"name":"1",
"value": "惠普"
},
{
"id":"2",
"css":"common",
"name":"2",
"value": "海爾"
},
{
"id":"3",
"css":"common",
"name":"3",
"value": "微星"
}
]
},
{
"title": "價格",
"name":"jiage",
"multiple": true,
"data": [
{
"id":"-1",
"css":"common",
"name":"1",
"value": "1-2999"
},
{
"id":"1",
"css":"common",
"name":"2",
"value": "3000-5000"
},
{
"id":"2",
"css":"common",
"name":"3",
"value": "5000-7000"
},
{
"id":"3",
"css":"common",
"name":"4",
"value": "7000-9000"
}
]
},
{
"title": "平臺",
"name":"pintai",
"multiple": false,
"data": [
{
"id":"-1",
"css":"common",
"name":"1",
"value": "全部"
},
{
"id":"1",
"css":"common",
"name":"2",
"value": "Inter平臺"
},
{
"id":"2",
"css":"common",
"name":"3",
"value": "AMD平臺"
},
{
"id":"3",
"css":"common",
"name":"4",
"value": "VDI平臺"
}
]
}
];
$('#filter').comboboxfilter({
scope: 'FilterQuery2',
data:data,
onChange:function(newValue){
$('#demo_value').val(newValue);
}
});
</script>
利用JSON封裝需要搜索條件字段,調用comboboxfilter自定義方法進行條件的初始化和動態搜索、展示功能。

下面對JS方法進行解釋:

/**
 * Author:mengbing
 * 
 * Date:2017-12-08
 * http://www.allenyMiky.com
 * 
 */
(function ($) {
    //初始化綁定事件
    $(function () {
       
    });
    $.fn.extend({
        comboboxfilter: function (ops) {
            if (typeof (arguments[0]) != typeof ("string")) {
                return $.fn.comboboxfilter.methods["init"](this, ops);
            } else {
                return $.fn.comboboxfilter.methods[arguments[0]](this, arguments);
            }
        }
    });


    //方法
    $.fn.comboboxfilter.methods = {
        options: function (target) {
            var opts = $(target).data("comboboxfilter").options;
            return opts;
        },
        init: function (target, ops) {
            var $this = this;
            var options = $.extend({}, $.fn.comboboxfilter.defaults, ops);
            $(target).data("comboboxfilter", { options: options });
$(target).removeClass('hotel-filter-list filter-list-has-more hotel-filter-list-min').addClass("hotel-filter-list filter-list-has-more hotel-filter-list-min");
           $.each(ops.data,function(key,value){
  
  var listcontainer = $('<div class="con"></div>').addClass(!value.multiple ? "radio" : "checkbox");
if (options.unlimit) {//添加條件集合名稱
var anyNode = $('<ul class="any filter-unlimit filter-tag selected"><li>'+ value.title + '</li></ul>');
listcontainer.append(anyNode);
}
$('.'+value.name).removeClass('hotel-filter-list filter-list-has-more hotel-filter-list-min').addClass("hotel-filter-list filter-list-has-more hotel-filter-list-min");
listcontainer.append('<ul class="list '+value.name+'"></ul>');
$(target).append(listcontainer);
$.fn.comboboxfilter.methods["load"](target,value);  
  
  });
//具有分組
if (options.scope) {
$(target).attr('scope', options.scope);//添加自定義分組屬性
if ($('#' + options.scope).length>0) {

} else {
var node = $('<div id="' + options.scope + '" class="hotel-filter-list "><strong class="tit">已選</strong><div class="con selected-query"><ul  class="list"><li class="filter-query-clear"><a class="J_FilterQueryClear" href="javascript:;">全部清除</a></li></ul></div></div>');
node.find('.J_FilterQueryClear').unbind('click').bind('click',function() {//全部清除事件
$('div[scope="' + options.scope + '"]').comboboxfilter('clear');
});
$('div[scope="' + options.scope + '"]:eq(0)').before(node);
}
}


        },
        load: function (target, opts) {
            var $this = this;
            var options = $.extend({}, $.fn.comboboxfilter.methods["options"](target), opts);
            if (opts.url) {
                $.ajax({
                    type: 'post',
                    data: options.param,
                    url: options.url,
                    success: function(data) {
                        if (typeof (data) == typeof ("string")) {
                            data = $.parseJSON(data);
                        }
                        var listTarget = $(target).find('.list').html('');
                        $this.setData(listTarget, options, data, target);
                    },
                    error: function(e) {
                        $this.onError(e);
                    }
                });
            } else {
var tag='.'+opts.name;
                var listTarget = $(target).find(tag).html('');
                $this.setData(listTarget, options, options.data, target);
            }
            
        },
        setData: function (target, options, data, targetContain) {
            var $this = this;
            $.each(data, function (i, item) {
                var listnode = $(' <li></li>');
                var clicka = $('<a class="filter-tag" href="javascript:;" data-value="' + item['value'] + '" data-text="' + item['value'] + '">' + item['value'] + '<i></i></a>').data('data', item['value']);
                clicka.unbind('click').bind('click', function (e) {
                    if (clicka.hasClass('selected')) {//驗證是否被選擇,已經選擇則取消選擇,反之選擇
                        clicka.removeClass('selected');//不可去掉(爲了計算Value的正確性)
                    } else {
                        if (!options.multiple) {//單選執行
var $list=$('#' + options.scope).find('li');
$.each($list,function(key,value){
var str=clicka.text();
$.each(options.data,function(n,m){
if(value.innerText==m.value){
$(value).remove();
$('.'+options.name).find('.selected').removeClass('selected');
}
});
});                                                      
                        }
                        clicka.addClass('selected');
                        $this.addSelected($('#' + options.scope), clicka, item, options, targetContain);//容器中添加選擇項
                    }
                    $this.reSetValue(targetContain); //重新計算Value
                    options.onClick(item);//觸發單機事件
                });
                listnode.append(clicka);
                target.append(listnode);
            });
            options.onLoadSuccess(data);//觸發加載完成事件
        },
        getValue: function(target) {
            var selected = $(target).find('.list .selected');
            var array = new Array();
            $.each(selected, function(i,item) {
                array.push($(item).attr('data-value'));
            });
            return array.join(",");
        },
        //添加已經選擇項
        //pointTarget:選擇項容器
        //target 被點擊的項
        //itemData 被選擇數據
        addSelected: function (pointTarget, target, itemData, options, targetContain) {
            var $this = this;
          var anode = $('<a href="javascript:;"><span data-category="'+options.name+'" name="'+itemData.name+'" class="'+itemData.css+'">' + itemData.value + '</span></a>');
                //創建X ,點擊則移除選擇項
                var inode = $('<i class="J_FilterQueryDel" data-type="ParentCatelog" data-value="' + itemData[options.idField] + '"></i>').unbind('click').bind('click', function (e) {
                    $(target).trigger("click.selected-tag");//觸發事件
                   // $(e.target).closest('.selected-tag').remove();
                    $this.reSetValue(targetContain); //重新計算Value
                });
                //綁定指定命名空間的單擊事件
                $(target).unbind('click.selected-tag').bind('click.selected-tag', function (e) {
                    $(target).removeClass('selected');
                    $(anode).closest('.selected-tag').remove();
                    $(target).unbind('click.selected-tag');
                });
                anode.append(inode);
                pointTarget.find('.list').append($('<li data-type="ParentCatelog" class="selected-tag"></li>').append(anode));
        },
        //重新計算Value
        reSetValue: function (target) {
            var value = this.getValue(target);
            $(target).find('input[name="' + this.options(target).inputName + '"]').val(value);
            //有值
            if (value) {
                $(target).find('.filter-unlimit').removeClass('selected');
            }
            //無值
            else {
                $(target).find('.filter-unlimit').addClass('selected');
            }
            this.options(target).onChange(value);
        },
        clear: function (target) {
            $(target).find('.selected').trigger("click.selected-tag");//觸發事件
            this.reSetValue(target); //重新計算Value
        }
    }
    $.fn.comboboxfilter.parseOptions = function (target) {
        return $.extend({}, $.fn.datagrid.parseOptions(target), {
        });
    };
   
    $.fn.comboboxfilter.defaults = {
        url: '',
        idField: 'id',
        textField: 'text',
        scope: 'FilterQuery',
        text: '',
        multiple: false,
   data:[],
        inputName: '',
        unlimit: true,//是否顯示不限,默認顯示
        unlimitText:'不限',
        param:{},
        onClick: function (itemData) { },
        onChange: function (newValue) { },
        onLoadSuccess: function (data) { },
        onError: function (e) { }
    };
})(jQuery);

extend方法首先用於自定義方法comboboxfilter。

$.fn.comboboxfilter.methods用於實現各個方法,其中init用於初始化,判斷展示的搜索條件是單選還是多選,並通過options初始化對展示的信息進行加載。

setData用於將JSON數據中的各個搜索字段加載到初始化的搜索欄目中。

addSelected方法用於對搜索條件進行選擇時加載到頂部的展示區域,或者是刪除頂部的已選擇搜索項。

reSetValue用於從新設定頂部搜索條件展示區數據。

代碼demo請至:http://download.csdn.net/download/zdxiaxiaxia/10152897


轉自:http://blog.csdn.net/zdxiaxiaxia/article/details/78765035

發佈了30 篇原創文章 · 獲贊 42 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章