Continue to post an article about the web front-end custom control - ComboBox (drop-down box). In the past, when I used the drop-down box control, I was always troubled by the ugly style. Now I share this control. I hope that useful colleagues can collect it or use it again. Modify to achieve the effect you want.
Decompose the custom drop-down box:
1. Create a constructor and initialize the assigned control value.
2. The bound control is presented in the foreground.
3. Click the drop-down box control to display the drop-down list
4. Click to trigger the drop-down box control and collapse the drop-down list.
5. Click the drop-down item to trigger the event.
The code is as follows:
Html code:
1. Custom class:
//下拉框
var ComboBox = function () {
this.tag;
this.data_default;
this.data_list;
this.index = 0;
var _this = this;
var _index, _tag, _value;
//初始化
this.init = function () {
_tag = _this.tag;
_index = _this.index;
//设置对象
_this.setDropdown(_this.data_default, _this.data_list);
//赋值绑定事件
if (_tag.find('span font').length > 0) _value = _tag.find('span font').attr('_id');
if (_tag == undefined) { return false; }
_this.showEvent();
_this.selectedIndex(_index);
return true;
}
//设置下拉列表
this.setDropdown = function (default_data, list) {
var css = _tag.attr('class');
if (default_data == undefined) {
default_data = { id: 'null', name: '' };
}
var _html = '';
if (_tag.find('p').length > 0 && _tag.find('span').length > 0) {
$.each(list, function (i, value) {
_html = '
' value.name '';
});
_tag.find('span font').replaceWith('
' default_data.name '');
_tag.find('p').html(_html);
} else {
_html = '
';
_html = '
' default_data.name '';
_html = '
';
if (list) {
$.each(list, function (i, value) {
_html = '' value.name '';
});
}
_html = '
';
_html = '
';
var parent = _tag.parent();
_tag.replaceWith(_html);
_tag = parent.find('.dropdown' (css.length > 0 ? '.' css.replace(' ', '.') : ''));
}
}
//下拉事件
this.showEvent = function () {
_tag.find('span').unbind('click').click(function () {
var p = $(this).parent().find('p');
if (p.css('display') == 'block') {
p.css('display', 'none');
$(this).removeClass('active');
} else if (p.html().length > 0) {
p.css('display', 'block');
$(this).addClass('active');
}
});
}
//选中事件
this.selectedIndex = function (index) {
_tag.find('p a').unbind('click').click(function () {
var parent = $(this).parent().parent();
//给下拉框赋值
if ($(this).text().length > 0) {
var font = parent.find('font');
font.text($(this).text());
font.attr("_id", $(this).attr('_id'));
_this.selectedIndexExpand(parent, $(this).index());
parent.find('span').removeClass('active');
}
parent.find('p').css('display', 'none');
});
if (_tag.find('p a').length <= _index) _index = 0;
if (_value && _value != '') {
_index = _tag.find('p a[_id="' _value '"]').index();
}
_tag.find('p a:eq(' _index ')').click();
}
//选中事件扩展
this.selectedIndexExpand = function (tag, index) { }
}