简体   繁体   English

jQuery select2 为所选项目添加类

[英]jQuery select2 add class to selected items

I want to be able to add a class to selected tags so that I can style them different colours.我希望能够为选定的标签添加一个类,以便我可以为它们设置不同的颜色。 Is there a way to do this?有没有办法做到这一点? As an example see the following:作为示例,请参见以下内容:

在此处输入图片说明

So if I wanted any category tags to be green, any location tags to be blue and any keyword tags to be red how would I do it.因此,如果我希望任何类别标签为绿色,任何位置标签为蓝色,任何关键字标签为红色,我该怎么做。 I have tried using the templateSelection option like so:我尝试过使用templateSelection选项,如下所示:

$('select').select2({
    templateSelection: function(item)
    {
        return '<span class="green">' + item.text + '</span>';
    }
});

But the HTML gets escaped so it shows the actual characters instead.但是 HTML 被转义了,所以它显示了实际的字符。 Plus this wouldn't add the class to the tag itself anyway.另外,这无论如何都不会将类添加到标签本身。

You can use that templateSelection and then search if it's a location or a keyword, and add escapeMarkup property:您可以使用该templateSelection ,然后搜索它是位置还是关键字,并添加escapeMarkup属性:

function template(data, container) {
  if(/Location\:/.test(data.text)) {
     return '<span class="location">'+data.text+'</span>';
  } else {
     return data.text;
  }
}

$('select').select2({
  templateSelection: template,
  escapeMarkup: function(m) { return m; }
});

Please, see it working:请看看它的工作原理:

https://jsfiddle.net/cz4ofkvg/1/ https://jsfiddle.net/cz4ofkvg/1/

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

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