javascript - 如何使用自定义匹配器通过多个搜索字符串进行 select2 过滤?
问题描述
我希望我的下拉列表按多个搜索字符串进行过滤,现在一次只能匹配 1 个匹配器字符串,这是所需的功能。
- 进入“红绿”时显示法拉利和雅马哈
我只有 Javascript 的基本知识,欢迎提琴。
提前致谢...
<html>
<head>
</head>
<body>
<form id="vehicle">
<select class="vehicles" name="gun" id="gun">
<option data-lookup="" value=""></option>
<option data-lookup="car, red" value="Ferarri">Ferarri</option>
<option data-lookup="bike, blue" value="Kawasaki">Kawasaki</option>
<option data-lookup="bike, green" value="Yamaha">Yamaha</option>
</select>
</form>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<!-- Sort dropdown alphabetically -->
<script>
$(document).ready(function() {
$('.vehicles').select2({
placeholder: "Enter search strings",
allowClear: true,
matcher: matchCustom
});
function matchCustom(params, data) {
// If there are no search terms, return all of the data
if ($.trim(params.term) === '') {
return data;
}
// Do not display the item if there is no 'text' property
if (typeof data.text === 'undefined') {
return null;
}
// `params.term` should be the term that is used for searching
// `data.text` is the text that is displayed for the data object
if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) > -1) {
return data;
}
// custom search using lookup data
if ($(data.element).data('lookup').toUpperCase().indexOf(params.term.toUpperCase()) > -1) {
return data;
}
// Return `null` if the term should not be displayed
return null;
}
});
</script>
</body>
</html>
解决方案
推荐阅读
- webpack - Webpack 不提供 css 文件
- sql - 来自具有可变数据库名称的多个数据库的 SQL“LEFT JOIN”
- java - 如何从 java 7 中的 .txt 文件中提取主机名和主机请求的出现?
- python - 在 python 中更改、重置和增加时间
- python - 具有有界队列的 Python ProcessPoolExecutor
- azure-blob-storage - 在 Azure 中下载和存储 GRIB2 文件
- java - Java 方法在 XML 的容器中创建数据点节点
- c++ - 将 int 数组转换为 std::vector
- sql - 如何避免列组织数据处理和行组织数据处理之间的转换
- mysql - 专用的 Celery 服务器会将 MySQL 查询的获取时间加倍吗?