【问题标题】:select2. js v4.0: how display and format local array data source?选择2。 js v4.0:如何显示和格式化本地数组数据源?
【发布时间】:2015-07-25 10:07:44
【问题描述】:

我正在使用 select2.js V4.0 (不是 3.6 !!!),我想显示和格式化 javascript 本地源代码:

var data_names = [{
  id: 0,
  text: "Henri",
  last_name: 'Barbusse'
}, {
  id: 1,
  text: "John",
  last_name: 'Lenon'
}, {
  id: 2,
  text: "Victor",
  last_name: 'Hugo'
}, {
  id: 3,
  text: "Marie",
  last_name: 'Stuart'
}, {
  id: 4,
  text: "Boriss",
  last_name: 'Vian'
}];

我的格式方法可以是例如:

function name_format(item) {
  if (!item.last_name) {
    return item.text;
  }
  var full_name = '<span class="my_class">' + item.text + ' ' + item.last_name + '</span>';
  return full_name;
}

你知道如何在 v4.0 中做到这一点吗?

【问题讨论】:

  • 根据 select2 文档:用户可以从中选择的对象应作为数组传递,每个对象包含 id 和 text 属性。不要认为他们改变了这一点
  • 谢谢,我已经编辑了我的问题

标签: javascript jquery jquery-select2 jquery-select2-4


【解决方案1】:

根据文档,您必须使用选项 templateResult

templateResult 函数应该返回一个包含要显示的文本的字符串,或者一个包含应该显示的数据的对象(例如 jQuery 对象)。它还可以返回null,这将阻止选项显示在结果列表中。

应该这样做

$('select').select2({
  multiple: true,
  data: data_names,
  templateResult: name_format
});

function name_format(item) {
  if (!item.last_name) {
    return item.text;
  }
  var full_name = $('<span class="my_class">' + item.text + ' ' + item.last_name + '</span>');
  return full_name;
}
$(function() {
  var data_names = [{
    id: 0,
    text: "Henri",
    last_name: 'Barbusse'
  }, {
    id: 1,
    text: "John",
    last_name: 'Lenon'
  }, {
    id: 2,
    text: "Victor",
    last_name: 'Hugo'
  }, {
    id: 3,
    text: "Marie",
    last_name: 'Stuart'
  }, {
    id: 4,
    text: "Boriss",
    last_name: 'Vian'
  }];
  $('select').select2({
    multiple: true,
    data: data_names,
    templateResult: name_format
  })
});
select {
  width: 250px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://select2.github.io/dist/js/select2.full.js"></script>
<link href="https://select2.github.io/dist/css/select2.min.css" rel="stylesheet" />
<select></select>

另外,name_format 方法应该返回一个 DOM/jQuery 对象而不是字符串。

function name_format(item) {
  if (!item.last_name) {
    return item.text;
  }
  var full_name = $('<span class="my_class">' + item.text+ ' ' + item.last_name+'</span>');
  return full_name;
}

【讨论】:

  • 谢谢! Dhiraj 它可以工作,但它显示原始文本而不解释 html
  • 见我回答的最后一部分。我提到过name格式方法应该返回一个dom对象
猜你喜欢
  • 2015-10-17
  • 2015-10-08
  • 2015-10-10
  • 1970-01-01
  • 2021-10-30
  • 1970-01-01
  • 1970-01-01
  • 2010-10-01
  • 2017-01-11
相关资源
最近更新 更多