Jquery 如何动态地将类添加到Selectize选项中?

Jquery 如何动态地将类添加到Selectize选项中?,jquery,css,selectize.js,Jquery,Css,Selectize.js,在向select输入添加选项时,使用jQuery有条件地添加类是很简单的: $("#mySelect").append( $("<option></option>") .text(myName) .val(myValue) .addClass(myBoolean ? "class1" : "class2") ); 在这里添加class选项不起作用,而且addOption()也不会返回任何内容,所以我一直在想该怎么

在向
select
输入添加选项时,使用jQuery有条件地添加类是很简单的:

$("#mySelect").append(
    $("<option></option>") 
        .text(myName)
        .val(myValue)
        .addClass(myBoolean ? "class1" : "class2")
);

在这里添加
class
选项不起作用,而且
addOption()
也不会返回任何内容,所以我一直在想该怎么做。有可能吗?

这是一个很好的案例

我写了一个简单的例子,说明了我认为您需要什么——标记有“favorite:true”属性的选项有一个新的类和样式,在SelectizeJS小部件中动态添加到这些选项中

selectize.plugins.js

Selectize.define('favorite_options', function(options) {
  options = $.extend({
        className : 'favorited'
    }, options);

  var favoriteOptionsClass = function(thisRef, options) {

    var self = thisRef;
    console.log({'self':self})

    var original = self.setup;
    self.setup = (function() {

        return function() {

          var option_render = self.settings.render.option;
          self.settings.render.option = function(option) {
            // "render" the original option to get the current HTML
            var html = option_render.apply(self, arguments);

            // modify HTML to add class
            var $html = $(html);
            var classes = $html.attr("class");

            if (option.favorite) {
              $html.addClass("favorite")
            }

            // return NEW $html element as HTML string
            return $('<div>').append($html.clone()).html();
          }

          original.apply(self, arguments);
        };
    })();
  }

  favoriteOptionsClass(this, options);
  return;
});
$("#wiki-select-property").selectize({
  maxItems: 1,
    valueField: 'id',
    labelField: 'title',
    searchField: 'title',
    plugins: [
      'favorite_options' 
    ],
    options: [
        {id: 1, title: 'Spectrometer', favorite: true, url: 'http://en.wikipedia.org/wiki/Spectrometers'},
        {id: 2, title: 'Star Chart', favorite: false,  url: 'http://en.wikipedia.org/wiki/Star_chart'},
        {id: 3, title: 'Electrical Tape', favorite: false,  url: 'http://en.wikipedia.org/wiki/Electrical_tape'}
    ]
})

您是否实例化了selectize插件?类似于:
var$select=$('#mySelect')。选择(选项)我确实有,是的。下拉菜单显示“良好…”。。。我只想能够添加一个类到选项。干杯
$("#wiki-select-property").selectize({
  maxItems: 1,
    valueField: 'id',
    labelField: 'title',
    searchField: 'title',
    plugins: [
      'favorite_options' 
    ],
    options: [
        {id: 1, title: 'Spectrometer', favorite: true, url: 'http://en.wikipedia.org/wiki/Spectrometers'},
        {id: 2, title: 'Star Chart', favorite: false,  url: 'http://en.wikipedia.org/wiki/Star_chart'},
        {id: 3, title: 'Electrical Tape', favorite: false,  url: 'http://en.wikipedia.org/wiki/Electrical_tape'}
    ]
})