Select2js插件无法选择任何选项

Select2 js Plugin Not able to select any option

本文关键字:任何 选项 选择 插件 Select2js      更新时间:2023-09-26

我正在使用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公告"页面上的"id和文本属性严格执行"部分:

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


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

您没有显示返回的data的样子,但从idtemplateResult函数来看,它似乎是一个具有以下属性的对象数组:interestIdtextdescription。在这种情况下,processResults函数可能看起来像这样:

// 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 };
},