xm-select多选下拉框实现拼音、首字母搜索匹配

前言

最近项目中遇到需要下拉框能实现根据首字母进行模糊搜索,下拉框使用的是xm-select,而xm-select支持中文的搜索,后端接口也仅支持中文的。因此需要借助其他插件来完成功能。

准备工作

  1. layui.js
  2. pinyin.js
  3. initials.js
  4. xm-select.js

代码

  1. 自定义搜索过滤器
typescript 复制代码
//搜索过滤器
var myFilter_xmSel = function (value, text, id) {
    //value:输入值; text:option的text值;id:option的value值;
     var result;
     if (escape(value).indexOf("%u") != -1) { //汉字
         result = text.indexOf(value) > -1;
     } else {
         var len = value.length;
         result = ConvertPinyin(text).substring(0, len) === value || makePy(text)[0].toLowerCase().substring(0, len) === value || text.toLowerCase().indexOf(value) > -1 || (id === undefined ? false : id.indexOf(value) > -1);
     }
     return result;
 };
  1. 下拉框初始化
typescript 复制代码
 let xmSel = xmSelect.render({
    el: '#sel',
    name: 'sel',
    model: {
        label: {
            type: 'text'
        }
    },
    radio: true,
    //选中关闭
    clickClose: true,
    filterable: true,
    filterMethod: function (val, item, index, prop) {//重写搜索方法。
        if (val == item.value) {//把value相同的搜索出来
            return true;
        }
        if (item.name.indexOf(val) != -1) {//名称中包含的搜索出来
            return true;
        }
        return myFilter_xmSel(val, item.name, item.value);
    },
    data:[你的数据]
})
相关推荐
早该学学了20 分钟前
el-tabs问题解决大总结
前端
中微子21 分钟前
回调函数详解:C++开发者视角下的JavaScript异步艺术
javascript
Sun_light21 分钟前
LeetCode 59.「螺旋矩阵」
javascript·算法·面试
星河丶22 分钟前
useEffect的清理函数的执行时机
前端·react.js
星河丶26 分钟前
React 的“组件即函数”理念
前端
星河丶27 分钟前
什么是React中的副作用
前端·react.js
星河丶27 分钟前
React 组件化的设计思想如何提升代码复用性
前端·react.js
猩猩程序员27 分钟前
Cargo使用指南 - 使用 Cargo 的第一步
前端
猩猩程序员27 分钟前
Cargo使用指南 - 安装
前端
Westrious28 分钟前
【JS里的小函数】帮助你在全局作用域中创建和访问对象的函数
前端·javascript·node.js