global var:
(function () { /** * FCZX.foo.bar */ let FCZX = {}; FCZX.globalNamespace = function (ns) { var nsParts = ns.split("."); var root = window; for (var i = 0; i < nsParts.length; i++) { if (typeof root[nsParts[i]] == "undefined") { root[nsParts[i]] = {}; } root = root[nsParts[i]]; } return root; } window.FCZX = FCZX; })()
下拉事件定义:
(function ($) { FCZX.globalNamespace('FCZX.Select'); FCZX.Select = function (opt) { this._init(opt) } $.extend(FCZX.Select.prototype, { _init: function (opt) { this.opt = { selectContS: '.select-content', //下拉框选择器 selectTextS: '.select-text', //选择项目显示, selectListS: '.select-list', //下拉选项框 optionS: 'li', //选项 dataProp: 'value', //取值key labelProp: 'label', //标签名取值key allValue: 'all' //当选择所有的时候值 } $.extend(true, this.opt, opt || {}); this._initDomEvent(); }, _initDomEvent: function () { let _this = this; let _opt = _this.opt; _this.$selectCont = $(_opt.selectContS); _this.$selectList = _this.$selectCont.find(_opt.selectListS); _this.$selectCont.each(function () { $(this).hover(function () { $(this).find(_opt.selectListS).show(); }, function () { $(this).find(_opt.selectListS).hide(); }); }) _this.$selectList.find(_opt.optionS).each(function () { $(this).on('click.selectOption', function () { let text = $(this).text() let value = $(this).data(_opt.dataProp); let selectText = $(this).parent().siblings(_opt.selectTextS); let $span = selectText.find('span'); let $input = selectText.find('input'); if (!value || value == _opt.allValue) { $span.text($span.data(_opt.labelProp)); $input.val(''); selectText.removeClass('actived'); } else { $span.text(text); $input.val(value); selectText.addClass('actived'); } _this.$selectList.hide(); $(_this).trigger('change', [$input]); }); }) } }); })(jQuery);
使用:
let selectS = new FCZX.Select(_opt.selectOpt); $(selectS).on('change', function (event, $input) { console.log($input) });