【问题标题】:Select2 load local json with multiple keysSelect2 使用多个键加载本地 json
【发布时间】:2016-01-30 16:29:18
【问题描述】:

在select2“加载远程数据”example 响应 json 包含比“加载数组数据”example2 更多的信息。

是否可以加载包含数组数据的本地json文件如下图 并使用 select2 使所有键可选择/可搜索,例如文本,文本2和文本3?

var data = [
  {
    id: 0,
    text: 'enhancement',
    text2: 'text2',
    text3: 'text3'
  },
  {
    id: 1,
    text: 'bug',
    text2: 'text2',
    text3: 'text3'
  },
  {
    id: 2,
    text: 'duplicate',
    text2: 'text2',
    text3: 'text3'
  },
  {
    id: 3,
    text: 'invalid',
    text2: 'text2',
    text3: 'text3'
  },
  {
    id: 4,
    text: 'wontfix',
    text2: 'text2',
    text3: 'text3'
  }
];

$(".js-example-data-array").select2({
  data: data
})

<select class="js-example-data-array"></select>

【问题讨论】:

    标签: javascript jquery json jquery-select2


    【解决方案1】:

    序言:我不使用这个库。

    查看 3.5.3 的文档。它列出了您可以编写的自定义匹配器,以根据添加到选择元素的属性匹配数据。 4.0 有包装器,您可以将它们添加到这些自定义匹配器中以使它们保持最新。

    这些自定义匹配器可以查看您对象中的任何数据。

    由于当前正在重写文档中的选项页面,请查看https://select2.github.io/options-old.html 并搜索“匹配器”选项。不要在这里使用示例:https://select2.github.io/examples.html#matcher 因为它只给你输入的术语和选项的文本。

    当您将选项传递给您的 select2 初始化程序时,请执行以下操作: (注意这是未经测试的代码)。

     $(".js-example-data-array").select2({
          data: data,
        matcher: function (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
    
          // here include conditions for each of the attributes you want to match on
          // I've included text and text2 as an example
          if (data.text.indexOf(params.term) > -1 || data.text2.indexOf(params.term) > 1) {
            return data;
          }
    
          // Return `null` if the term should not be displayed
          return null;
        }
    })
    

    祝你好运。

    【讨论】:

      猜你喜欢
      • 2018-05-11
      • 2017-06-25
      • 1970-01-01
      • 2013-08-12
      • 2014-10-09
      • 1970-01-01
      • 2018-07-28
      • 1970-01-01
      相关资源
      最近更新 更多