Select2:自定义匹配器 - 通过数据阵列搜索



我正在与 select2

给定此示例JSON数据:

{"id":1,"text":"search term category","data":[{"Key":"catalog","Value":"search term catalog"},{"Key":"make","Value":"search term make"},{"Key":"model","Value":"search term model"}]}

我如何不仅可以搜索" text" 字段,还可以搜索" value" 字段中的所有 data> data Array array

我阅读了有关自定义匹配器的阅读

希望您可以帮助我或为我提供样本。

谢谢。

编辑:小提琴:jsfiddle

您需要编写一个自定义匹配器,在Select2文档中提供了示例。我修改了他们提供的示例,以使其可能对您有用。

function matchCustom(params, data) {
    // If there are no search terms, return all of the data
    if ($.trim(params.term) === '') {
      return data;
    }
    // `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.indexOf(params.term) > -1) {
      return data;
    }
    // checking if a value matches (my addition to their example)
    if (data.data.some(({Value}) => Value.includes(params.text)) {
      return data;
    }
    // Return `null` if the term should not be displayed
    return null;
}
$(".js-example-matcher").select2({
  matcher: matchCustom
});

您可能必须修改我的添加功能,以匹配您的浏览器兼容性要求(即我使用脂肪箭头功能,对象破坏,String.prototype.includesArray.prototype.some(。

最新更新