简体   繁体   English

标记时Select2模板不会自动完成

[英]Select2 template does not autocomplete when tagging

I'm trying to use Select2.js version 4.0 to create tag selections. 我正在尝试使用Select2.js 4.0版创建标签选择。 I would like a new tag to be created if it doesn't exit, and I would like the results formatted using a 'data-html' tag. 如果不退出,我希望创建一个新标签,并且我希望使用'data-html'标签格式化结果。

The problem is that the two elements( createTag and templateResult ) work independently, but when I use them together the autocomplete options no longer show up when an user types in the search box. 问题在于这两个元素( createTagtemplateResult )是独立工作的,但是当我一起使用它们时,当用户在搜索框中键入内容时,自动完成选项将不再显示。

Am I doing something wrong, or is this a limitation of Select2? 我是在做错什么,还是Select2的限制?

application.js application.js

  $("#taglist").select2({
    tokenSeparators: [',', ' '],
    tags: true,
    createTag: function (tag) {
        // Case insensitive search for tag
        tagExists = false;
        $("#taglist option").each(function() {
            if ($.trim(tag.term).toUpperCase() == $.trim($(this).text()).toUpperCase()) {
                tagExists = true;
            }
        });

        // If the tag does not exist create it
       if (!tagExists) {
             return {
                id: tag.term,
                text: tag.term + " (create)",
                isNew: true
            };
        }
    },
    templateResult: function (choice) {
      if (!choice.id) { return choice.text; }
      var $choice = $(
        '<span><a>' + data.element.getAttribute('data-html') + '</a></span>' 
      );
      return $choice;
    }
  });

There is no data.element when tagging, so your templating methods need to be able to handle that. 标记时没有data.element ,因此您的模板方法必须能够处理该问题。 Ideally, your methods should be able to work with data.text and anything else would be optional. 理想情况下,您的方法应该能够使用data.text而其他任何方法都是可选的。

So you should be falling back to data.text if there is nothing in the data-html attribute on the element. 因此,如果该元素的data-html属性中没有任何内容,您应该回到data.text

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM