我正在使用Select2.js(最新版本)在我的应用程序中实现标记化的标记。一切正常,除了我无法从建议中选择任何项目。

我看到很少有人提到需要在配置中包含“ id”的答案。它似乎对我不起作用。

我的代码是:

$("#interest").select2({ ajax: {
            url: "get-interests",
            dataType: 'json',
            delay: 250,
            data: function (params) {
              return {
                q: params.term, // search term
                page: params.page
              };
            },
            processResults: function (data, page) {
              // parse the results into the format expected by Select2.
              // since we are using custom formatting functions we do not need to
              // alter the remote JSON data
              return {
                results: data
              };
            },
            cache: true
          },
          escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
          placeholder:{
              id: "-1",
              text: "Add your interest.."
          } ,
          tags: true,
          tokenSeparators: [',', ' '],
          id: function(data) {
              alert(JSON.stringify(data));
              return data.interestId;
          },
          templateResult: function(post) {
              // return html markup for individual result item
              var markup ="";
              if(String(post.description) !== 'undefined') {
                 markup = '<p><b>' + post.text + '</b>  : ' + post.description + '</p>';
              } else {
                 markup = '<p><b>' + post.text + '</b></p>';
              }
              return markup;
           },
           formatSelection: function(post) {
              // This shows up in the select box
              return post.text;
           }


我在上述配置中做错了什么?

最佳答案

与您在代码中放置的注释相反,对于Select2 4.0,您确实需要向processResults函数添加代码以将返回的JSON数据转换为具有id属性的对象。通常,对象还应该具有text属性,但是如果您提供templateResulttemplateSelection函数,则不必。


  我看到很少有人提到我们需要包括的答案
  在我们的配置中为“ id”。它似乎对我不起作用。


这些答案对于早期版本的Select2是正确的,但对于Select2 v4.0,不再支持id功能。请参见"4.0 Anouncement"页上的“严格执行id和text属性”部分:

您也可以删除formatSelection功能。在Select2 4.0中,它现在应命名为templateSelection。这意味着没有为您调用它,但是您可能没有注意到,因为您的formatSelection函数只是在做默认情况下要做的事情。



processResults函数应返回具有results属性的对象,该属性设置为对象数组。这些对象都需要具有id属性(但是它们也可以具有其他属性)。

您没有显示返回的data的样子,但是从idtemplateResult函数来看,它似乎是具有以下属性的对象数组:interestIdtext和。在这种情况下,您的description函数可能如下所示:

// This builds a new array of new objects.
processResults: function(data, page) {
    return {
        results: $.map(data, function(post) {
            return {
                id: post.interestId,
                text: post.text,
                description: post.description
            };
        })
    };
},


或这个:

// This just adds an `id` property to the objects in the existing array.
processResults: function(data, page) {
    $.each(data, function(i, post) {
        post.id = post.interestId;
    });
    return { results: data };
},

09-25 17:49
查看更多