将jquery插件应用到第二个Select时

时间:2015-11-12 15:37:10

标签: jquery

我有一个页面显示选择主要类别,当您选择一个选项时,会出现第二个选择(带子类别)。

问题是第二个Select不是由jquery插件转换的,因为只有在我从第一个Select中选择一个选项后(以及页面完全加载时)才会加载它。 那么,任何想法如何使它适用于第二选择?可以吗?

我没有放置第二个选择因为我不知道如何在第一次选择时单击选项时加载它。

两个Select都来自php文件,你可以在https://demo.osclass.org/general/index.php?page=item&action=item_add

上看到它们

/*
 * jQuery Selectbox plugin 0.2
 *
 * Copyright 2011-2012, Dimitar Ivanov (http://www.bulgaria-web-developers.com/projects/javascript/selectbox/)
 * Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) license.
 *
 * Date: Tue Jul 17 19:58:36 2012 +0300
 */
(function($, undefined) {
  var PROP_NAME = "selectbox",
    FALSE = false,
    TRUE = true;

  function Selectbox() {
    this._state = [];
    this._defaults = {
      classHolder: "sbHolder",
      classHolderDisabled: "sbHolderDisabled",
      classSelector: "sbSelector",
      classOptions: "sbOptions",
      classGroup: "sbGroup",
      classSub: "sbSub",
      classDisabled: "sbDisabled",
      classToggleOpen: "sbToggleOpen",
      classToggle: "sbToggle",
      classFocus: "sbFocus",
      speed: 200,
      effect: "slide",
      onChange: null,
      onOpen: null,
      onClose: null
    }
  }
  $.extend(Selectbox.prototype, {
    _isOpenSelectbox: function(target) {
      if (!target) {
        return FALSE
      }
      var inst = this._getInst(target);
      return inst.isOpen
    },
    _isDisabledSelectbox: function(target) {
      if (!target) {
        return FALSE
      }
      var inst = this._getInst(target);
      return inst.isDisabled
    },
    _attachSelectbox: function(target, settings) {
      if (this._getInst(target)) {
        return FALSE
      }
      var $target = $(target),
        self = this,
        inst = self._newInst($target),
        sbHolder, sbSelector, sbToggle, sbOptions, s = FALSE,
        optGroup = $target.find("optgroup"),
        opts = $target.find("option"),
        olen = opts.length;
      $target.attr("sb", inst.uid);
      $.extend(inst.settings, self._defaults, settings);
      self._state[inst.uid] = FALSE;
      $target.hide();

      function closeOthers() {
        var key, sel, uid = this.attr("id").split("_")[1];
        for (key in self._state) {
          if (key !== uid) {
            if (self._state.hasOwnProperty(key)) {
              sel = $("select[sb='" + key + "']")[0];
              if (sel) {
                self._closeSelectbox(sel)
              }
            }
          }
        }
      }
      sbHolder = $("<div>", {
        id: "sbHolder_" + inst.uid,
        "class": inst.settings.classHolder,
        tabindex: $target.attr("tabindex")
      });
      sbSelector = $("<a>", {
        id: "sbSelector_" + inst.uid,
        href: "#",
        "class": inst.settings.classSelector,
        click: function(e) {
          e.preventDefault();
          closeOthers.apply($(this), []);
          var uid = $(this).attr("id").split("_")[1];
          if (self._state[uid]) {
            self._closeSelectbox(target)
          } else {
            self._openSelectbox(target)
          }
        }
      });
      sbToggle = $("<a>", {
        id: "sbToggle_" + inst.uid,
        href: "#",
        "class": inst.settings.classToggle,
        click: function(e) {
          e.preventDefault();
          closeOthers.apply($(this), []);
          var uid = $(this).attr("id").split("_")[1];
          if (self._state[uid]) {
            self._closeSelectbox(target)
          } else {
            self._openSelectbox(target)
          }
        }
      });
      sbToggle.appendTo(sbHolder);
      sbOptions = $("<ul>", {
        id: "sbOptions_" + inst.uid,
        "class": inst.settings.classOptions,
        css: {
          display: "none"
        }
      });
      $target.children().each(function(i) {
        var that = $(this),
          li, config = {};
        if (that.is("option")) {
          getOptions(that)
        } else {
          if (that.is("optgroup")) {
            li = $("<li>");
            $("<span>", {
              text: that.attr("label")
            }).addClass(inst.settings.classGroup).appendTo(li);
            li.appendTo(sbOptions);
            if (that.is(":disabled")) {
              config.disabled = true
            }
            config.sub = true;
            getOptions(that.find("option"), config)
          }
        }
      });

      function getOptions() {
        var sub = arguments[1] && arguments[1].sub ? true : false,
          disabled = arguments[1] && arguments[1].disabled ? true : false;
        arguments[0].each(function(i) {
          var that = $(this),
            li = $("<li>"),
            child;
          if (that.is(":selected")) {
            sbSelector.text(that.text());
            s = TRUE
          }
          if (i === olen - 1) {
            li.addClass("last")
          }
          if (!that.is(":disabled") && !disabled) {
            child = $("<a>", {
              href: "#" + that.val(),
              rel: that.val()
            }).text(that.text()).bind("click.sb", function(e) {
              if (e && e.preventDefault) {
                e.preventDefault()
              }
              var t = sbToggle,
                $this = $(this),
                uid = t.attr("id").split("_")[1];
              self._changeSelectbox(target, $this.attr("rel"), $this.text());
              self._closeSelectbox(target)
            }).bind("mouseover.sb", function() {
              var $this = $(this);
              $this.parent().siblings().find("a").removeClass(inst.settings.classFocus);
              $this.addClass(inst.settings.classFocus)
            }).bind("mouseout.sb", function() {
              $(this).removeClass(inst.settings.classFocus)
            });
            if (sub) {
              child.addClass(inst.settings.classSub)
            }
            if (that.is(":selected")) {
              child.addClass(inst.settings.classFocus)
            }
            child.appendTo(li)
          } else {
            child = $("<span>", {
              text: that.text()
            }).addClass(inst.settings.classDisabled);
            if (sub) {
              child.addClass(inst.settings.classSub)
            }
            child.appendTo(li)
          }
          li.appendTo(sbOptions)
        })
      }
      if (!s) {
        sbSelector.text(opts.first().text())
      }
      $.data(target, PROP_NAME, inst);
      sbHolder.data("uid", inst.uid).bind("keydown.sb", function(e) {
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0,
          $this = $(this),
          uid = $this.data("uid"),
          inst = $this.siblings("select[sb='" + uid + "']").data(PROP_NAME),
          trgt = $this.siblings(["select[sb='", uid, "']"].join("")).get(0),
          $f = $this.find("ul").find("a." + inst.settings.classFocus);
        switch (key) {
          case 37:
          case 38:
            if ($f.length > 0) {
              var $next;
              $("a", $this).removeClass(inst.settings.classFocus);
              $next = $f.parent().prevAll("li:has(a)").eq(0).find("a");
              if ($next.length > 0) {
                $next.addClass(inst.settings.classFocus).focus();
                $("#sbSelector_" + uid).text($next.text())
              }
            }
            break;
          case 39:
          case 40:
            var $next;
            $("a", $this).removeClass(inst.settings.classFocus);
            if ($f.length > 0) {
              $next = $f.parent().nextAll("li:has(a)").eq(0).find("a")
            } else {
              $next = $this.find("ul").find("a").eq(0)
            } if ($next.length > 0) {
              $next.addClass(inst.settings.classFocus).focus();
              $("#sbSelector_" + uid).text($next.text())
            }
            break;
          case 13:
            if ($f.length > 0) {
              self._changeSelectbox(trgt, $f.attr("rel"), $f.text())
            }
            self._closeSelectbox(trgt);
            break;
          case 9:
            if (trgt) {
              var inst = self._getInst(trgt);
              if (inst) {
                if ($f.length > 0) {
                  self._changeSelectbox(trgt, $f.attr("rel"), $f.text())
                }
                self._closeSelectbox(trgt)
              }
            }
            var i = parseInt($this.attr("tabindex"), 10);
            if (!e.shiftKey) {
              i++
            } else {
              i--
            }
            $("*[tabindex='" + i + "']").focus();
            break;
          case 27:
            self._closeSelectbox(trgt);
            break
        }
        e.stopPropagation();
        return false
      }).delegate("a", "mouseover", function(e) {
        $(this).addClass(inst.settings.classFocus)
      }).delegate("a", "mouseout", function(e) {
        $(this).removeClass(inst.settings.classFocus)
      });
      sbSelector.appendTo(sbHolder);
      sbOptions.appendTo(sbHolder);
      sbHolder.insertAfter($target);
      $("html").live("mousedown", function(e) {
        e.stopPropagation();
        $("select").selectbox("close")
      });
      $([".", inst.settings.classHolder, ", .", inst.settings.classSelector].join("")).mousedown(function(e) {
        e.stopPropagation()
      })
    },
    _detachSelectbox: function(target) {
      var inst = this._getInst(target);
      if (!inst) {
        return FALSE
      }
      $("#sbHolder_" + inst.uid).remove();
      $.data(target, PROP_NAME, null);
      $(target).show()
    },
    _changeSelectbox: function(target, value, text) {
      var onChange, inst = this._getInst(target);
      if (inst) {
        onChange = this._get(inst, "onChange");
        $("#sbSelector_" + inst.uid).text(text)
      }
      value = value.replace(/\'/g, "\\'");
      $(target).find("option[value='" + value + "']").attr("selected", TRUE);
      if (inst && onChange) {
        onChange.apply((inst.input ? inst.input[0] : null), [value, inst])
      } else {
        if (inst && inst.input) {
          inst.input.trigger("change")
        }
      }
    },
    _enableSelectbox: function(target) {
      var inst = this._getInst(target);
      if (!inst || !inst.isDisabled) {
        return FALSE
      }
      $("#sbHolder_" + inst.uid).removeClass(inst.settings.classHolderDisabled);
      inst.isDisabled = FALSE;
      $.data(target, PROP_NAME, inst)
    },
    _disableSelectbox: function(target) {
      var inst = this._getInst(target);
      if (!inst || inst.isDisabled) {
        return FALSE
      }
      $("#sbHolder_" + inst.uid).addClass(inst.settings.classHolderDisabled);
      inst.isDisabled = TRUE;
      $.data(target, PROP_NAME, inst)
    },
    _optionSelectbox: function(target, name, value) {
      var inst = this._getInst(target);
      if (!inst) {
        return FALSE
      }
      inst[name] = value;
      $.data(target, PROP_NAME, inst)
    },
    _openSelectbox: function(target) {
      var inst = this._getInst(target);
      if (!inst || inst.isOpen || inst.isDisabled) {
        return
      }
      var el = $("#sbOptions_" + inst.uid),
        viewportHeight = parseInt($(window).height(), 10),
        offset = $("#sbHolder_" + inst.uid).offset(),
        scrollTop = $(window).scrollTop(),
        height = el.prev().height(),
        diff = viewportHeight - (offset.top - scrollTop) - height / 2,
        onOpen = this._get(inst, "onOpen");
      el.css({
        top: height + "px",
        maxHeight: (diff - height) + "px"
      });
      inst.settings.effect === "fade" ? el.fadeIn(inst.settings.speed) : el.slideDown(inst.settings.speed);
      $("#sbToggle_" + inst.uid).addClass(inst.settings.classToggleOpen);
      this._state[inst.uid] = TRUE;
      inst.isOpen = TRUE;
      if (onOpen) {
        onOpen.apply((inst.input ? inst.input[0] : null), [inst])
      }
      $.data(target, PROP_NAME, inst)
    },
    _closeSelectbox: function(target) {
      var inst = this._getInst(target);
      if (!inst || !inst.isOpen) {
        return
      }
      var onClose = this._get(inst, "onClose");
      inst.settings.effect === "fade" ? $("#sbOptions_" + inst.uid).fadeOut(inst.settings.speed) : $("#sbOptions_" + inst.uid).slideUp(inst.settings.speed);
      $("#sbToggle_" + inst.uid).removeClass(inst.settings.classToggleOpen);
      this._state[inst.uid] = FALSE;
      inst.isOpen = FALSE;
      if (onClose) {
        onClose.apply((inst.input ? inst.input[0] : null), [inst])
      }
      $.data(target, PROP_NAME, inst)
    },
    _newInst: function(target) {
      var id = target[0].id.replace(/([^A-Za-z0-9_-])/g, "\\\\$1");
      return {
        id: id,
        input: target,
        uid: Math.floor(Math.random() * 99999999),
        isOpen: FALSE,
        isDisabled: FALSE,
        settings: {}
      }
    },
    _getInst: function(target) {
      try {
        return $.data(target, PROP_NAME)
      } catch (err) {
        throw "Missing instance data for this selectbox"
      }
    },
    _get: function(inst, name) {
      return inst.settings[name] !== undefined ? inst.settings[name] : this._defaults[name]
    }
  });
  $.fn.selectbox = function(options) {
    var otherArgs = Array.prototype.slice.call(arguments, 1);
    if (typeof options == "string" && options == "isDisabled") {
      return $.selectbox["_" + options + "Selectbox"].apply($.selectbox, [this[0]].concat(otherArgs))
    }
    if (options == "option" && arguments.length == 2 && typeof arguments[1] == "string") {
      return $.selectbox["_" + options + "Selectbox"].apply($.selectbox, [this[0]].concat(otherArgs))
    }
    return this.each(function() {
      typeof options == "string" ? $.selectbox["_" + options + "Selectbox"].apply($.selectbox, [this].concat(otherArgs)) : $.selectbox._attachSelectbox(this, options)
    })
  };
  $.selectbox = new Selectbox();
  $.selectbox.version = "0.2"
})(jQuery);


$(document).ready(function(){
$("select").selectbox({
    effect: "fade"
});
$("#select_2").selectbox({
    effect: "fade"
});
});
.sbHolder {
  background-color: #2d2d2d;
  border: solid 1px #515151;
  font-family: Arial, sans-serif;
  font-size: 12px;
  font-weight: normal;
  height: 30px;
  position: relative;
  width: 200px;
}
.sbHolder:focus .sbSelector {} .sbSelector {
  display: block;
  height: 30px;
  left: 0;
  line-height: 30px;
  outline: none;
  overflow: hidden;
  position: absolute;
  text-indent: 10px;
  top: 0;
  width: 170px;
}
.sbSelector:link,
.sbSelector:visited,
.sbSelector:hover {
  color: #EBB52D;
  outline: none;
  text-decoration: none;
}
.sbToggle {
  background: url(../img/select-icons.png) 0 -116px no-repeat;
  display: block;
  height: 30px;
  outline: none;
  position: absolute;
  right: 0;
  top: 0;
  width: 30px;
}
.sbToggle:hover {
  background: url(../img/select-icons.png) 0 -167px no-repeat;
}
.sbToggleOpen {
  background: url(../img/select-icons.png) 0 -16px no-repeat;
}
.sbToggleOpen:hover {
  background: url(../img/select-icons.png) 0 -66px no-repeat;
}
.sbHolderDisabled {
  background-color: #3C3C3C;
  border: solid 1px #515151;
}
.sbHolderDisabled .sbHolder {} .sbHolderDisabled .sbToggle {} .sbOptions {
  background-color: #212121;
  border: solid 1px #515151;
  list-style: none;
  left: -1px;
  margin: 0;
  padding: 0;
  position: absolute;
  top: 30px;
  width: 200px;
  z-index: 1;
  overflow-y: auto;
}
.sbOptions li {
  padding: 0 7px;
}
.sbOptions a {
  border-bottom: dotted 1px #515151;
  display: block;
  outline: none;
  padding: 7px 0 7px 3px;
}
.sbOptions a:link,
.sbOptions a:visited {
  color: #ddd;
  text-decoration: none;
}
.sbOptions a:hover,
.sbOptions a:focus,
.sbOptions a.sbFocus {
  color: #EBB52D;
}
.sbOptions li.last a {
  border-bottom: none;
}
.sbOptions .sbDisabled {
  border-bottom: dotted 1px #515151;
  color: #999;
  display: block;
  padding: 7px 0 7px 3px;
}
.sbOptions .sbGroup {
  border-bottom: dotted 1px #515151;
  color: #EBB52D;
  display: block;
  font-weight: bold;
  padding: 7px 0 7px 3px;
}
.sbOptions .sbSub {
  padding-left: 17px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<select id="select_1">
  <option value="0">Select category</option>
  <option value="109">Category 1</option>
  <option value="118">Category 2</option>
  <option value="121">Category 3</option>
  <option value="122">Category 4</option>
  <option value="123">Category 5</option>
</select>

2 个答案:

答案 0 :(得分:0)

将插件应用于第一个select

的方式相同
$("select").selectbox({
    effect: "fade"
});

您只需在创建第二个select 后再次执行此插件初始化

请注意,如果插件初始化以任何方式重置第一个select或者由于某种原因,元素不能/不应该使用插件多次初始化,那么您可能希望更具体地识别jQuery选择器中的目标元素。因此,例如,如果第二个select具有特定的id,那么您可以将其作为目标:

$("#theSecondSelectID").selectbox({
    effect: "fade"
});

答案 1 :(得分:0)

您可以在&#34; onChange&#34;上创建并触发第二个选择元素的选择框。功能。这是你在寻找什么?

$("select").selectbox({
    effect: "fade",
    onChange: function(e){
        var sbVal = $("#secondSelect").attr("sb");
        $("#sbHolder_" + sbVal).remove();
        $("#secondSelect").remove();

        $("body").append("<select id='secondSelect' />");
        $("#secondSelect").append("<option>"+e+"</option>");
        $("#secondSelect").selectbox({
            effect: "fade"
        });
    }
});

https://jsfiddle.net/rs9boo6L/3/