您的位置:首页 > Web前端 > JQuery

基于JSON+JQuery实现的多条件筛选功能(类似京东和淘宝功能)

2017-12-10 15:38 856 查看
首先声明,是在已有的方法基础上进行完善的,转载请标明出处。

首先看一下实现效果:



现在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

个人原创,转载请注明出处!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: