JS组件系列
前言:在介绍select组件的时候,博主之前分享过一篇 JS组件系列——两种bootstrap multiselect组件大比拼 ,这两个组件的功能确实很强大,只可惜没有图文结合的效果(也就是将图片放入到select里面随着文字一起显示)。前两天做一个菜单图标选择的功能,就要用到这个图文选择的功能。于是乎又是找啊找。终于不负所望,找到了我们伟大的select2组件。今天分享下这个组件的一些用法和特性。 一、组件说明以及API说明Select2使用示例地址: https://select2.github.io/examples.html Select2参数文档说明: https://select2.github.io/options.html Select2源码: https://github.com/select2/select2 二、组件特性效果展示一些通用的单选、多选、分组等功能这里就不多做介绍了,multiselect这方面是强项。重点介绍下select2的一些特性效果: 1、多选效果
可以设置最多只能选几个
2、图文结合的效果
3、远程搜索功能(即在用户输入搜索内容时动态去后台取数据)输入内容前
输入空格搜索出全部
滚动条滑动到底部自动加载剩余项
输入文本动态去后台过滤
更高级的用法如:
其实使用起来也不难,就是一个拼html的过程。 三、代码示例1、多选效果select2的多选很简单,设置一个属性就好了。 //多选 $("#sel_menu2").select2({ tags: true, maximumSelectionLength: 3 //最多能够选择的个数 }); 2、图文结合的效果$(function () { //带图片 $("#sel_menu").select2({ templateResult: formatState, templateSelection: formatState });});function formatState(state) { if (!state.id) { return state.text; } var $state = $( ' 3、远程搜索功能(即在用户输入搜索内容时动态去后台取数据)$(function () { //远程筛选 $("#sel_menu3").select2({ ajax: { url: "/Home/GetProvinces", dataType: 'json', delay: 250, data: function (params) { return { q: params.term, // search term page: params.page }; }, processResults: function (data, params) { params.page = params.page || 1; return { results: data.items, pagination: { more: (params.page * 10) < data.total_count } }; }, cache: true }, escapeMarkup: function (markup) { return markup; }, // let our custom formatter work minimumInputLength: 1, templateResult: formatRepoProvince, // omitted for brevity, see the source of this page templateSelection: formatRepoProvince // omitted for brevity, see the source of this page });}); function formatRepoProvince(repo) { if (repo.loading) return repo.text; var markup = ""+repo.name+""; return markup;} 这里有要注意的一个地方就是processResults属性对应的方法有一个more属性用于是否分页显示的,这里的值要和你需要一次显示的值的条数匹配。 后台对应的方法如下: public List |