首页 > 解决方案 > 如何使用自定义匹配器通过多个搜索字符串进行 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>

标签: javascriptjqueryjquery-select2

解决方案


推荐阅读