选项HTML,更改SelectBox插件的默认结构

时间:2015-05-18 09:06:06

标签: javascript jquery

我在这个编码世界中有点新鲜,所以对我来说这看起来很简单,但我无法解决它。给我这种痛苦的功能是

function _renderOptions() {
  var optionHTML = [];

  $options.each(function(i, itm) {
    var $this = $(this),
      optgroup = $this.parents('optgroup'),
      addlOptClasses = "",
      iconMarkup = "";

    // render optgroups if present in original select
    if (optgroup.length > 0 && $this.prev().length === 0) {
      optionHTML.push('<dt>' + optgroup.attr('label') + '</dt>');
    }

    // if option has a classname add that to custom select as well
    if (itm.className !== "") {
      $(itm.className.split(" ")).each(function() {
        iconMarkup += '<span class="' + this + '"></span>';
      });
    }

    // add selected class to whatever option is currently active
    if (itm.selected && !itm.disabled) {
      _selectedValue = iconMarkup + _truncate($(itm).html());
      addlOptClasses = " " + SELECTED_CLASS;
    }

    // Check for disabled options
    if (itm.disabled) {
      addlOptClasses += " " + DISABLED_CLASS;
    }

    optionHTML.push('<dd class="itm-' + i + ' ' + addlOptClasses + '">' + iconMarkup + itm.innerHTML + '</dd>');
  });

  if ($selectedValue && $selectedValue.get(0) !== null) {
    $selectedValue.html(_selectedValue);
  }

  return optionHTML.join("");
}

我想要的是,如果选项具有类名,则在<dd>的类中添加相同的类,而不是创建<span>并在那里添加类

1 个答案:

答案 0 :(得分:1)

从该项中取出该类,并将其添加到dd元素:optionHTML.push('<dd class="itm-' + i + ' ' + addlOptClasses + ' ' + $(itm).attr("class") + '">' + iconMarkup + itm.innerHTML + '</dd>');

function _renderOptions() {
  var optionHTML = [];

  $options.each(function(i, itm) {
    var $this = $(this),
      optgroup = $this.parents('optgroup'),
      addlOptClasses = "",
      iconMarkup = "";

    // render optgroups if present in original select
    if (optgroup.length > 0 && $this.prev().length === 0) {
      optionHTML.push('<dt>' + optgroup.attr('label') + '</dt>');
    }

    // if option has a classname add that to custom select as well
    if (itm.className !== "") {
      $(itm.className.split(" ")).each(function() {
        iconMarkup += '<span class="' + this + '"></span>';
      });
    }

    // add selected class to whatever option is currently active
    if (itm.selected && !itm.disabled) {
      _selectedValue = iconMarkup + _truncate($(itm).html());
      addlOptClasses = " " + SELECTED_CLASS;
    }

    // Check for disabled options
    if (itm.disabled) {
      addlOptClasses += " " + DISABLED_CLASS;
    }

    optionHTML.push('<dd class="itm-' + i + ' ' + addlOptClasses + ' ' + $(itm).attr("class") + '">' + iconMarkup + itm.innerHTML + '</dd>');
  });

  if ($selectedValue && $selectedValue.get(0) !== null) {
    $selectedValue.html(_selectedValue);
  }

  return optionHTML.join("");
}