select2搜索-仅匹配以搜索词开头的单词 [英] select2 search - match only words that start with search term

查看:58
本文介绍了select2搜索-仅匹配以搜索词开头的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从选择迁移到select2插件,因为它对我来说效果更好,但是与选择相比,它的文档非常差.谁能告诉我应该使用哪种选项来使select2搜索功能筛选出仅以搜索词开头的单词(并且不要在中间包含该单词).

I migrated from chosen to select2 plugin because it works better for me, but its documentation is very poor when compared to chosen. Could anyone tell me what option(s) should be used to make select2 search function to filter words that just begin with search term (and don't contain it in the middle).

假设select2字段具有以下选项:香蕉,苹果,菠萝.

Let's say select2 field has those options: banana, apple, pineapple.

当用户输入"app"(或apple)时,仅应返回apple(因为这是唯一以apple开头的单词).现在,它同时返回苹果和菠萝.

When user enters "app" (or apple), only apple should be returned (because it's the only word that starts with apple). Now, it returns both apple and pineapple.

经过大量搜索,我发现需要使用一些自定义匹配器,但到目前为止.

After lots of search I figured out that some custom matcher needs to be used, but that's all so far.

推荐答案

Select2提供了文档中的示例有关如何使用自定义matcher函数将搜索词与搜索结果进行匹配的信息.给出的示例就是这个确切的用例.

Select2 provides an example in the documentation on how to use a custom matcher function for matching search terms to search results. The example given is this exact use case.

function matchStart (term, text) {
  if (text.toUpperCase().indexOf(term.toUpperCase()) == 0) {
    return true;
  }
 
  return false;
}
 
$.fn.select2.amd.require(['select2/compat/matcher'], function (oldMatcher) {
  $("select").select2({
    matcher: oldMatcher(matchStart)
  })
});

<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.css" rel="stylesheet"/>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.full.js"></script>

<select style="width: 200px">
  <option value="AL">Alabama</option>
  <option value="AK">Alaska</option>
  <option value="AZ">Arizona</option>
</select>

这篇关于select2搜索-仅匹配以搜索词开头的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆