在 select2 的选项中搜索多个单词

search for multiple words in an option in select2

我用select2
结果,我在后端有一个列表

[
  [12, "red fast car1"],
  [45, "red big car2"],
  [56, "red small table1"],
  [34, "red fast car3"],
  [77, "red big table"]
]

根据要求'red car' 需要获取列表:

用什么火柴?
我的 fiddle

您可以在每个 <space> 和 return 拆分 term 仅当 every 单个单词匹配 textlabel 时才为真

  const terms = term.split(' ');

  return terms.every(term => {
     if (text.indexOf(term) > -1 ||
        (label !== undefined &&
           label.toUpperCase().indexOf(term) > -1)) {
        return true;
     }
  })

Updated fiddle

我偶然发现了这个话题,感谢您指出您可以在 select2 中使用自定义匹配器。

尽管如此,the interface seems to have changed 因为你写了 fiddle,所以这里是我不得不用 coffeescript 写的改编(⚠️ 我不使用 optgroups):

$ ->
  matcher = (params, data) ->
    if !params.term?
      return data

    terms = params.term.toUpperCase().split(' ')
    text = data.text.toUpperCase()

    if terms.every((term) -> return true if text.indexOf(term) > -1)
      return data
    else
      return null


  $('.selectpicker').select2({matcher: matcher});