jQuery Select2 显示的选择有问题

jQuery Select2 issue with shown selection

我正在开发一个 select 菜单,我在其中使用 Select-2 插件来自定义它。因此,我遇到了一个问题,我尝试在输入字段中重新创建 selected 项目。因此,当您 select 一个项目时,它在输入字段中显示为灰色列表中的小项目。

这是一个 FIDDLE,它显示了我遇到的问题。

这是 javascript 我如何呈现输入字段的代码:

var selectMenuItems = [
        {id: 'restaurant', value: 'restaurant'},
        {id: 'shopping', value: 'shopping'},
        {id: 'toilet', value: 'toilet'}
    ]

     function formatSelectItem (selectItem) {
        if (!selectItem.id) { return selectItem.value; }
        var $selectItem = $(
        '<img src="img/markers/'+ selectItem.id.toLowerCase() +'.png"/>' +
        '<span class="select-item-text">'+ selectItem.value+"</span>"
        );
        return $selectItem;
    };

    $("[name='select']").select2({
        placeholder: "Selecteer een categorie",
        templateResult: formatSelectItem,
        data: selectMenuItems
    }).on("change", function(e){
        console.log(e);

        $('.select-multiple :selected').each(function(i, selected) {
            var selectedValue = $(selected).val();

            $('.select2-selection__choice').text(selectedValue);
        });
    });

问题是,当我 select 一个项目时,它会在输入字段中显示文本,但如果我 select 多个,所有项目将更改为最后一个 selected 项目文本。我怎样才能只将这个 .text() 绑定到那个特定的 select 项目?

在插件 Select-2 plugin 的文档中有一个名为 "Templating" 的示例,其中他们不必将文本或图像附加到 selected 项目..

在你的代码中

        $('.select-multiple :selected').each(function(i, selected) {
            var selectedValue = $(selected).val();

            $('.select2-selection__choice').text(selectedValue);
        });

您需要将 selectedValue 拆分为值并搜索每个值以放入适合该值索引的文本。

换句话说,将代码替换为:

     $('.select-multiple :selected').each(function(i, selected) {
        var selectedValue = $(this).val();
        $('.select2-selection__choice').eq(i).text(selectedValue);
      });

Working fiddle.

您要查找的是每次循环遍历 $(this).val() 提供的选定值并使用 .eq() 将值附加到 .select2-selection__choice 索引:

$("[name='select']").select2({
  placeholder: "Selecteer een categorie",
  templateResult: formatSelectItem,
  data: selectMenuItems
}).on("change", function(e){
  $.each($(this).val(), function(i, selected) {
    $('.select2-selection__choice').eq(i).prepend(selected+' ');
  });
});

注意: 使用 prepend() 而不是 tex() 来保留标签中的 'X'。

希望对您有所帮助。

(function($) {
  $(function() {
    var selectMenuItems = [
      {id: 'restaurant', value: 'restaurant'},
      {id: 'shopping', value: 'shopping'},
      {id: 'toilet', value: 'toilet'}
    ]

    function formatSelectItem (selectItem) {
      if (!selectItem.id) { return selectItem.value; }
      var $selectItem = $(
        '<img src="img/markers/'+ selectItem.id.toLowerCase() +'.png"/>' +
        '<span class="select-item-text">'+ selectItem.value+"</span>"
      );
      return $selectItem;
    };

    $("[name='select']").select2({
      placeholder: "Selecteer een categorie",
      templateResult: formatSelectItem,
      data: selectMenuItems
    }).on("change", function(e){
      $.each($(this).val(), function(i, selected) {
        $('.select2-selection__choice').eq(i).prepend(selected+' ');
      });
    });

  });
})(jQuery);            
.flag-text { margin-left: 10px; }

.select2 {
  width: 100% !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
<select id="type" name="select" class="select-multiple" multiple="multiple" data-role="none"></select>

使用图片的片段:

(function($) {
  $(function() {
    var selectMenuItems = [
      {id: 'restaurant', value: 'restaurant', img: 'https://www.hughesinsurance.co.uk/img/front/map-marker.png'},
      {id: 'shopping', value: 'shopping', img: 'http://king-of-truck.byclickeat.fr/media/cache/square_40/front/bundle/clickeat/img/map-marker.png'},
      {id: 'toilet', value: 'toilet', img: 'http://www.onebabyowner.co.uk/sites/all/themes/onebabyowner/img/icon/map-marker.png'}
    ]

    function formatSelectItem (selectItem) {
      if (!selectItem.id) { return selectItem.value; }
      var $selectItem = $(
        '<img src="'+ selectItem.img +'"/>' +
        '<span class="select-item-text">'+ selectItem.value+"</span>"
      );
      return $selectItem;
    };

    $("[name='select']").select2({
      placeholder: "Selecteer een categorie",
      templateResult: formatSelectItem,
      data: selectMenuItems
    }).on("change", function(e){
      $.each($(this).val(), function(i, selected) {
        $('.select2-selection__choice').eq(i).prepend(selected+' ');
      });
    });

  });
})(jQuery);            
.flag-text { margin-left: 10px; }

.select2 {
  width: 100% !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
<select id="type" name="select" class="select-multiple" multiple="multiple" data-role="none"></select>

这是最短的方法:

$('.select-multiple :selected').each(function(i, selected) {
   $('.select2-selection__choice').eq(i).text($(this).val());
});

如果要在所选选项中包含图像,请使用 templateSelection function.You 可以通过将 templateSelection 选项设置为 JavaScript 函数来覆盖所选内容的显示.

(function($) {
        $(function() {
            var selectMenuItems = [
               {id: 'restaurant', text: 'restaurant', img: 'http://www.freeiconspng.com/uploads/restaurant-icon-png-7.png'},
               {id: 'shopping', text: 'shopping', img: 'http://www.pngall.com/wp-content/uploads/2016/04/Shopping-Free-PNG-Image.png'},
               {id: 'toilet', text: 'toilet', img: 'http://www.freeiconspng.com/uploads/toilet-icon-png-32.png'}
            ]

            function formatSelectItem (selectItem) {
                if (!selectItem.id) { return selectItem.text; }
                var $selectItem = $(
                    '<img src="'+ selectItem.img +'" width="50px" height="50px"/>' +
                    '<span class="select-item-text">'+ selectItem.text+"</span>"
                );
               return $selectItem;
            };
            function formatState (opt) {
                if (!opt.id) {
                   return opt.text;
                }                               
                var $opt = $(
                  '<span><img src="'+opt.img +'" width="50px" height="50px"/>' + opt.text + '</span>'
                );
                return $opt;
            };
            $("[name='select']").select2({
               placeholder: "Selecteer een categorie",
               templateResult: formatSelectItem,
               templateSelection: formatState,
               data: selectMenuItems
            });
            
        });
})(jQuery);            
.flag-text { margin-left: 10px; }

.select2 {
  width: 100% !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
<select id="type" name="select" class="select-multiple" multiple="multiple" data-role="none"></select>

我以为我必须用 jquery 来做这个,但是当我将 selectMenuItems valueArray 更改为 text 时,插件会为我完成工作:

 var selectMenuItems = [
   {id: 'restaurant', text: 'restaurant'},
   {id: 'shopping', text: 'shopping'},
   {id: 'toilet', text: 'toilet'}
 ]

只是一个简单的修复,我认为我可以在那里设置任何 属性