;
(function ($) {
$.fn.ajaxDropSelect = function (op) {
op.param = op.param || {}; // ajax额外参数
op.enter = op.enter || $.noop; // 确认选中后的执行函数
op.callfn = op.callfn || $.noop; // 异步请求到数据后执行的回调函数
op.onfn = op.onfn || $.noop; // 按上下键选中条目后执行的函数
op.focus = op.focus || $.noop; // 输入框聚焦时执行的函数
op.blur = op.blur || $.noop; // 输入框聚焦时执行的函数
// op.click = op.click || $.noop; // 鼠标点击菜单项后执行的函数
op.onclass = op.onclass || 'on'; // 选中状态的classname
op.ablenum = op.ablenum === undefined ? 3 : op.ablenum; // 指定字符长度以上才执行ajax请求
op.skin = op.skin || 'ajaxDropSelect'; // 指定样式名
op.jump = op.jump || ''; // 选项中可能存在需要跳过的项目
op.delay = op.delay || 500; // 两次按键之间的延迟 防止按键太快请求
this.each(function () {
var that = this;
var $t = $(that);
var url = op.url;
var type = op.type;
var data = {};
that.val = '';
$.extend(data, op.param);
$t.after('<ul class="' + op.skin + '"></ul>');
var ul = $t.next().hide();
var onfnres;
var selIndex;
var bool = true;
$t.keypress(function (e) {
if (e.which == 13) {
$t.blur();
return op.enter();
}
}).keyup(function (e) {
var item = ul.children('li');
if (op.jump) {
item = item.not(op.jump);
}
var key = e.which;
var val = $.trim(this.value);
if (key == 38) { // 向上
if (selIndex === undefined || selIndex === 0) {
selIndex = item.length - 1;
} else {
selIndex--;
}
} else if (key == 40) { // 向下
if (selIndex === undefined || selIndex === item.length - 1) {
selIndex = 0;
} else {
selIndex++;
}
}
if (~$.inArray(key, [38, 40])) {
clearTimeout(that.timer);
item.removeClass(op.onclass).eq(selIndex).addClass(op.onclass);
op.onfn({
that: $t,
list: ul,
selIndex: selIndex,
data: onfnres || {}
});
} else {
$t.trigger('focus')
}
return false;
}).blur(function () {
clearTimeout(that.timer);
setTimeout(function () {
ul.hide();
op.blur({
that: $t,
list: ul,
selIndex: selIndex,
data: onfnres || {}
});
}, 200);
}).focus(function (e) {
clearTimeout(that.timer);
// 解决中文输入出现的一些问题
that.timer = setInterval(function () {
var val = $t.val().trim();
// 有新的输入
if (val && val != that.val) {
that.val = val;
data[$t.attr("name")] = val;
$.ajax({
url: url,
data: data,
type: type,
dataType: 'json',
success: function (m) {
onfnres = m;
op.callfn({
that: $t,
list: ul,
data: m || {}
});
_ul();
}
});
}
}, op.delay + 50)
_ul();
op.focus({
that: $t,
list: ul,
selIndex: selIndex,
data: onfnres || {}
});
});
ul.on('click', 'li', function () {
if ($(this).parent()[0] === ul[0] && !$(this).hasClass(op.jump)) {
var ele = ul.children();
if (op.jump) {
ele = ele.not(op.jump);
}
op.onfn({
that: $t,
list: ul,
selIndex: ele.index(this),
data: onfnres || {}
});
op.enter();
}
})
function _ul() {
if (ul.children().length) {
ul.show();
}
}
});
}
})($);