`

jquery autocomplete && linkage

 
阅读更多

参考网上已有的combobox,经过改造与完善,特分享一下。

支持一下特性:

1.下拉条目自定义展示

2.加载过程中友好信息提示

3.与linkage配合,方便构造联动(国家/区域)

不足之处,

1.使用jquery position插件定位下拉位置,自身实现缺有些瑕疵

2.供职公司要求URL参数定制化太重,JS代码嵌入postdata校验

3.linakge缓存算法太差
.c-list {
	overflow:auto;
	position: absolute;
	z-index: 999999;
	display: none;
	border: 1px solid #CCCCCC;
	background-color: white;
	left:-9999px;
	top:-9999px;
}

.c-list .item {
	display:block;
	overflow: hidden;
	word-break: normal;
	word-wrap: break-word;
	cursor: pointer;
	padding: 2px 0px 2px 5px;
	border-bottom: 1px dashed #CCCCCC;
}

.c-list .item-selected {
	background: #c8e3fc;
}
 
;(function($) {
	
	$.i18n=$.i18n || {};
	$.i18n.autocomplete={
		NO_DATA:'没有数据',
		LOAD_ERROR:'加载异常',
		LOAD_TEXT:'努力加载中...'
	};
	
	if (!$.browser) {
		var userAgent = navigator.userAgent.toLowerCase();
		// Figure out what browser is being used
		$.browser = {
			version : (userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [])[1],
			safari : /webkit/.test(userAgent),
			opera : /opera/.test(userAgent),
			chrome: /chrome/.test(userAgent),
			msie : /msie/.test(userAgent) && !/opera/.test(userAgent),
			mozilla : /mozilla/.test(userAgent)
					&& !/(compatible|webkit)/.test(userAgent)
		};
	}

	/** 高版本浏览器支持 **/
	var ele = document.createElement("input");
	var _support_placeholder = 'placeholder' in ele;

	ele = null;

	/**
	 * autocomplete
	 * @constructor
	 */
	$.autocomplete = function($element, options) {
		var self = this,input = $element[0],name=options.name || input.name;
		this.$element = (options.cls ? $element : $element.addClass(options.cls)).removeAttr("name");
		input.autocomplete = 'off';
		input.value='';
		
		this.records=[];
		
		// 选中记录索引
		this._selected_=-1;
		
		// ajax请求路径
		this.url = options.url;
		
		// ajax请求额外参数
		this.urlParams = options.urlParams;

		// ajax请求查找数据记录顶层节点 
		this.dataRoot=options.dataRoot;

		// ajax请求延迟
		this.delay = options.delay;

		// 请求后台数据条数限制,靠后台实现
		this.start=0;
		this.limit = options.limit;
		
		// 录入最少字符数
		this.minChars = options.minChars;

		// 隐藏值域
		this.valueField = options.valueField;
	
		// 显示域
		this.displayField = options.displayField;

		// 有时候需要获得下拉框数据对应的文本描述
		this.textField=options.textField || (name+"name");
		
		// 后台查询过滤字段
		this.queryField = options.queryField || this.displayField;
		
		// 下拉条目模板
		this.tpl = "<li class='item' data-index='<% i %>'>" + (options.tpl || '<% item.'+this.displayField+'%>') + "</li>";

		// 浏览器placeholder
		var ph = options.placeholder;
		if (ph) {
			_support_placeholder ? $element.attr("placeholder", ph)
					: this.placeholder = ph;
		} else {
			if (!_support_placeholder) {
				ph = $element.attr("placeholder");
				if (ph) {
					this.placeholder = ph;
					$element.removeAttr("placeholder");
				}
			}
		}
		
		// 只读状态
		this._readOnly=false;
		options.readOnly || $element.prop("readOnly") ? this.readOnly(true) : false;

		// 隐藏域DOM
		this.$hidden = $("<input type='hidden' ignoreElement='true' name='"+ name + "' />").appendTo(input.parentNode);
		
		// 下拉DOM
		this.$list=$('<div class="c-list auto-list{cls}"><ul></ul></div>'.replace(/{cls}/,options.listCls ? ' '+ options.listCls: '')).appendTo(document.body);
		options.listWidth && this.$list.width(options.listWidth==='force' ? this.$element.outerWidth() - (this.$list.outerWidth() - this.$list.width()) : options.listWidth);
		options.listHeight && this.$list.height(options.listHeight);

		// 使用本地缓存
		this._use_cache = !!options.useCache;
		if (this._use_cache) {
			this._cache_data = {};
			this._cache_length = 0;
			this._cache_size = options.cacheSize;
		}

		// set value
		this.reset(options.value || '');

		// 事件
		$element.focus(function() {

			var sf=self;
			
			// 只读
			if(sf.isReadOnly()){return true;}
			
			var $this=$(this);
		
			// 已聚焦
			if ($this.hasClass("focus")) {return true;};
			
			// 聚焦样式
			$this.removeClass("placeholder").addClass("focus");
			
			// placeholder文本处理(IE6/7/8)
			var ph=sf.placeholder,v=this.value;
			ph && v === ph ? this.value='' : sf.selectRange(0,v.length);

			// 触发事件
			sf.trigger("focus");

			// 下拉DOM已显示
			if(sf.isActive()){return true;}

			// 展示下拉DOOM
			sf.records.length && sf.show();

		}).blur(function() {

				var sf=self;
			
				// 只读
				if(sf.isReadOnly()){return true;}
			
				// IE doesn't prevent moving focus even with event.preventDefault()
				if (sf._ignore_blur_) {this.focus();sf.selectRange(0, this.value.length);sf._ignore_blur_ = false;return false;}
	
				// 聚焦样式
				$(this).removeClass("focus");
	
				// 设值
				sf.value(sf._selected_!=-1 ? sf.records[sf._selected_] : null);
				
				// 隐藏下拉
				sf.hide();
				
				// 触发事件
				sf.trigger("blur");
				
				// 校验 
				sf.validate(sf.value());

		}).click(function() {
			
			var sf=self;
			
			// 只读
			if(sf.isReadOnly()){return true;}
			
			// 下拉DOM已显示
			if(sf.isActive()){return true;}

			// 展示下拉DOOM
			sf.records.length && sf.show();

		}).keydown(function(e) {
			
			var sf=self;
			
			// 只读
			if(sf.isReadOnly()){return false;}

			switch (e.keyCode) {

				case 38: // up
					
					sf.isActive() && sf.focus('prev');
					
					return false;

				case 40: // down

					sf.isActive() ? sf.focus('next') : ( sf.records.length ? sf.show() : sf.activate());
					
					return false;

				case 9: // tab
					
					return true;
					
				case 13: // enter
					
					sf.isActive() && sf.select() && sf.selectRange(0, this.value.length);

					return false;

				case 27: // escape
					
					// Different browsers have different default behavior for escape
					// Single press can mean undo or clear
					// Double press in IE means clear the whole form
					// e.preventDefault();
					
					sf.isActive() && sf.hide();
					
					return false;
				case 37 : // left
					
					sf.isActive() && sf.hide();
					
					return false;
					
				case 39 : // right
					
					!sf.isActive() && !sf.records.length && sf.activate();
					
					return false;
				case 33 : // page up
					
					sf.isActive() && sf.focus('pageprev');
					
					return false;
				case 34 : // page down
					
					sf.isActive() && sf.focus('pagenext');
					
					return false;
				case 36 : // home
					
					sf.isActive() && sf.focus('first');
					
					return false;
				case 35 : // end
					
					sf.isActive() && sf.focus('last');
					
					return false;
				default:

					sf._selected_ = -1;
				
					sf._activate_timer_ && clearTimeout(sf._activate_timer_);
					
					sf._activate_timer_ = setTimeout(function() {sf.activate();}, sf.delay);

				}
		}).on("input.autocomplete",function(){
			
			// FIREFOX
			var sf=self;
			
			if(sf.isReadOnly()){return false;}
			
			sf._selected_ = -1;
			
			sf._activate_timer_ && clearTimeout(sf._activate_timer_);
			
			sf._activate_timer_ = setTimeout(function() {sf.activate();}, sf.delay);
		
		});
		
		// 为表格编辑器做铺垫,必须做判断
		var celleditor=options.celleditor;
		
		this.$list.on("mouseover.autocomplete", " > ul > li", function(e) {
			
			self.focus($(this));
			
		}).on("click.autocomplete", " > ul > li", function(e) {
			
			self.select($(this));
			
		}).mousedown(function(e) {
			
			// prevent moving focus out of the text field
			e.preventDefault();

			// @IE6/7/8 even prevent default behavior , blur event triggered also
			self._ignore_blur_ = $.browser.msie && (+$.browser.version) < 9;
			
			// 为表格编辑器做铺垫,必须做判断 
			return celleditor ? false : true;
			
		}).scroll(function(e){return false;});

	};

	// 下拉DOM展开状态
	$.autocomplete.prototype.isActive = function() {return this.$list[0].style.display === 'block';};

	// 显示下拉DOM
	$.autocomplete.prototype.show = function() {
		
		// 只读
		if(this.isReadOnly()){return this;}

		// 定位下拉DOM位置
		this.position();
		
		// 鼠标悬浮第N条
		this.focus(this._selected_ == -1 ? 0 : this._selected_);

		// 触发事件
		!this.isActive() && this.trigger("active");
		
		return this;
	};

	// 隐藏下拉DOM
	$.autocomplete.prototype.hide = function() {
		
		// 只读
		if(this.isReadOnly()){return this;}

		// 已隐藏
		if(!this.isActive()){return this;}
		
		this.$list[0].style.display = 'none';
		
		// 触发事件
		this.trigger("deactive");
		
		return this;
	}
	
	// 下拉DOM位置
	$.autocomplete.prototype.position=function(){
	
		this.$list[0].style.display='block';
		
		// jQuery position插件
		if ($.ui && $.fn.position) {
			
			this.$list.position( {
				my : "left top",
				at : "left bottom",
				collision : "fit",
				of : this.$element
			});
			
			return this;
		}
			
		// 默认配置,尽量避免 
		var offset = this.$element.offset();
		this.$list.css( {
			top : (offset.top + this.$element[0].offsetHeight) + 'px',
			left : offset.left + 'px'
		});

		return this;
	};

	// 读取远程数据
	$.autocomplete.prototype.activate = function() {

		var text = this.$element[0].value;
		
		// IE6/7/8
		this.placeholder && text == this.placeholder ? text = '' : false;
		
		// 特殊字符处理
		text=text.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
		
		// 最近一次查询
		if(this._last_query===text){return this;}
		
		// 最少字符数
		if(this.minChars && this.minChars > text.length){return this;}

		this._last_query=text;

		// 创建请求参数
		var opts={};
		opts[this.queryField]=text;
		
		// 分页
		if(this.limit > 0){
			opts.start= this.start ;
			opts.limit=this.limit;
		}

		// 发送请求
		this.load(opts);
		
		return this;
	};
	
	// 下拉DOM交互信息
	$.autocomplete.prototype.notice = function(msg) {
		
		var $ul=this.$list.find("> ul");
		
		// 正在加载远程数据 
		if(msg==='load'){
			$ul.html("<li class='notice load'>"+$.i18n.autocomplete.LOAD_TEXT+"</li>");
			return this;
		}
		
		// 无数据
		if(msg==='empty'){
			$ul.html("<li class='notice empty'>"+$.i18n.autocomplete.NO_DATA+"</li>");
			return this;
		}
		
		$ul.html(msg);
		
		return this;
	};
	
	// 请求远程数据
	$.autocomplete.prototype.load = function(opts, callback) {
		
		var self = this,cache,cacheKey;
		
		// ajax
		this._ajax_request && this._ajax_request.abort();

		typeof opts == 'function' ? (callback=opts,opts={}) : false;
		
		// 深度拷贝&&重载
		opts=$.extend(true,{},this.urlParams,opts);

		// 触发事件
		this.trigger("beforeload",opts);
		
		// 联动框需要缓存
		cacheKey=this.queryField && opts[this.queryField];
		
		// 为了配合后台框架必须做的
		if(opts.postdata && typeof opts.postdata == 'object'){
			
			var sc=opts.searchcondition=opts.searchcondition || {};
			
			this.queryField ? sc[this.queryField]=opts[this.queryField] : false;
			
			$.toJSON ? opts.postdata=$.toJSON(opts.postdata) : false;
		}

		// 回调函数
		var ajaxCallback = function(data) {

			var sf=self,dataRoot=self.dataRoot;
			
			data && dataRoot && data[dataRoot] ? data=data[dataRoot] : false;
			
			data= data || [];
			
			sf._selected_= -1;
			
			// 缓存写入
			sf.writeCache(cacheKey, data);
			
			// 执行回调函数
			typeof callback == 'function' && callback.call(sf, data);

			sf.json2Html(data);

			// 触发事件 
			sf.trigger("load",data);

			sf.isActive() && sf.show();
		};
						
		// 加载信息
		this.notice('load').show();
		
		// 如果使用缓存的话
		cache=cacheKey && this.readCache(cacheKey);
		if(cache){ajaxCallback(cache);return this;}

		var url=opts.url || this.url;
		delete opts.url;

		// ajax请求
		this._ajax_request=$.ajax( {
			url : url,
			data : opts,
			method : 'POST',
			dataType : 'json',
			success : ajaxCallback,
			error : function() {ajaxCallback(false);}
		});


		return this;
		
	};

	// 鼠标悬浮
	$.autocomplete.prototype.focus = function($item) {

		var cls="item-selected",$ul=this.$list.find("> ul");
		
		// 具体某条
		if($item instanceof jQuery){
		
			!$item.hasClass(cls) && $ul.find(" > li."+cls).removeClass(cls);
		
		}
		
		// 具体某条
		if(typeof $item == 'number'){
			
			$item=$ul.find(" > li.item:eq("+$item+")");
			
			if(!$item.length){return this;}
			
			!$item.hasClass(cls) && $ul.find(" > li."+cls).removeClass(cls);
		}

		// 下一条
		if($item == 'next'){
					
			$item=$ul.find(" > li."+cls).removeClass(cls);
			
			if(!$item.length){return this;}

			$item=$item.next();

			!$item.length ? $item=$ul.find("> li.item:eq(0)") : false;

		}
				
		// 上一条
		if($item == 'prev'){
			
			$item=$ul.find(" > li."+cls).removeClass(cls);
			
			if(!$item.length){return this;}

			$item=$item.prev();

			!$item.length ? $item=$ul.find("> li.item:last-child") : false;

		}
		
		// 第一条
		if($item == 'first'){
			
			$ul.find(" > li."+cls).removeClass(cls);

			$item=$ul.find(" > li.item:eq(0)");

			if(!$item.length){return this;}
		}
		
		// 最后一条
		if($item == 'last'){
			
			$ul.find(" > li."+cls).removeClass(cls);

			$item=$ul.find("> li.item:last-child");

			if(!$item.length){return this;}
		}

		// 上一页
		if($item == 'pageprev'){
			return this.focus("first");
		}
		
		// 下一页
		if($item == 'pagenext'){
			return this.focus("last");
		}
		
		if(!($item instanceof jQuery) || !$item.length){return this;}
		
		$item.addClass(cls);
		
		this.scroll($item);
		
		return this;
		
	};

	// 滚动视图
	$.autocomplete.prototype.scroll = function( $item ) {

		var $list=this.$list,list=$list[0];
		
		if($list.outerHeight() >= $list.prop( "scrollHeight" )){return this;}
		
		var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight;
	
		var borderTop = parseFloat( $.css( list, "borderTopWidth" ) ) || 0,paddingTop = parseFloat( $.css( list, "paddingTop" ) ) || 0;
		var offset = $item.offset().top - $list.offset().top - borderTop - paddingTop,scroll = $list.scrollTop();
		var elementHeight = $list.height(),itemHeight = $item.outerHeight();
		
		if ( offset < 0 ) {
			
			$list.scrollTop( scroll + offset + 17 );
		
		} else {
			if ( offset + itemHeight > elementHeight ) {
				
				//横向滚动条高度
				var scrollbar=0;
				if($list.outerWidth() <= $list.prop( "scrollWidth" )){scrollbar=$.position && $.position.scrollbarWidth && $.position.scrollbarWidth() || 17;}
		
				$list.scrollTop( scroll + offset - elementHeight + itemHeight + scrollbar );	

			}
		}

		return this;
	},

	// 鼠标点选
	$.autocomplete.prototype.select = function($item) {
		
		// 序号
		var index = typeof $item =='number' ? $item : -1;

		// enter key press
		$item ===  undefined && this.isActive() ? $item = this.$list.find("> ul > li.item-selected") : false;

		// DOM
		$item instanceof jQuery ? index = +$item.data("index") : false;

		var record=this.records[index];
		
		this._selected_ !== index && this.trigger("beforeselect",record);

		this.$hidden[0].value = record[this.valueField];
		
		this.$element[0].value = record[this.displayField];

		this._selected_ !== index  && this.trigger("select",record);
		
		this._selected_ = index;
		
		this.hide();

		return this;
	};

	// MY GOD DOM
	$.autocomplete.prototype.selectRange = function(start, end) {
		
		var input = this.$element[0];
		
		if (input.setSelectionRange) {
		
			input.focus();
			input.setSelectionRange(start, end);
		
		} else if (input.createTextRange) {
			
			var range = input.createTextRange();
			
			range.collapse(true);
			
			range.moveEnd('character', end);
			
			range.moveStart('character', start);
		
			range.select();
		
		}
		
		return this;
	};

	// 查找记录
	$.autocomplete.prototype.find = function(key, value) {
		var records=this.records || [],l = records.length;
		
		// 根据索引查找
		if (typeof key == 'number') 
			return l > key ? records[key] : null;

		// 根据属性查找,如name:'tom'
		while (l--)
			if (records[l][key] == value)
				return records[l];

		return null;
	};

	// 查找记录索引
	$.autocomplete.prototype.indexOf = function(key, value) {
		// 一个参数
		arguments.length == 1 && (value=key,key=this.valueField);

		// 参数为记录
		typeof value == 'object' ? value = value[this.valueField] : false;
		
		var records=this.records || [],l = records.length;
		
		while(l--)
			if(records[l][key]== value)
				return l;
		
		return -1;
	};

	// 缓存读取
	$.autocomplete.prototype.readCache = function(cacheKey) {
		
		this._cache_data=this._cache_data || {};
		
		if(this._use_cache && cacheKey){
			
			var cache=this._cache_data[cacheKey];
			
			// 最近经常使用
			cache ? cache.count=(cache.count || 0) + 1 : false;
			
			return cache ? cache.data : null;
		}
		
		return null;
		
	};

	// 缓存写入
	$.autocomplete.prototype.writeCache = function(cacheKey, data) {
		
		this._cache_data=this._cache_data || {};
		
		if(this._use_cache && cacheKey && data){
			
			// 清空缓存,应该搞个算法,最近很少使用
			if(this._cache_length > this._cache_size){
				
				this._cache_data={};
				
				this._cache_length=0;
			
			}
			
			this._cache_length++;
			this._cache_data[cacheKey]={data:data,count:0};
		}
		
		return this;
	
	};

	// JSON数据转化为HTML字符串
	$.autocomplete.prototype.json2Html = function(json, template) {
		
		var tplEngine = function(tpl, data) {
		    var reg = /<%([^%>]+)?%>/g, 
		        regOut = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g, 
		        code = 'var r=[];\n', 
		        cursor = 0;
		 
		    var add = function(line, js) {
		        js? (code += line.match(regOut) ? line + '\n' : 'r.push(' + line + ');\n') :
		            (code += line != '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' : '');
		        return add;
		    }
		    while(match = reg.exec(tpl)) {
		        add(tpl.slice(cursor, match.index))(match[1], true);
		        cursor = match.index + match[0].length;
		    }
		    add(tpl.substr(cursor, tpl.length - cursor));
		    code += 'return r.join("");';
		    return new Function(code.replace(/[\r\t\n]/g, '')).apply(data);
		};
		
		template=template || this.tpl;
		var code='<% for(var i=0,l=this && this.length || 0;i<l;i++){var item=this[i]; %>'+
				 template+
				 '<% } %>';
		
		this.records=json;
		
		this.notice(json.length===0 ? 'empty' : tplEngine(code,json));
		
		return this;

	}
	
	// 文本框文本
	$.autocomplete.prototype.text=function(){
		
		var text=this.$element[0].value;
		
		return this.placeholder && text===this.placeholder ? "" : text;
	};
	
	// 校验
	$.autocomplete.prototype.validate=function(){return $.validate ? $.validate(this.$element) : true;};

	// 只读
	$.autocomplete.prototype.isReadOnly=function(){return this._read_only===true;};
	
	// 设置只读
	$.autocomplete.prototype.readOnly = function(readOnly) {
		
		readOnly=!!readOnly;
		
		this._read_only=readOnly;
	
		this.$element[readOnly ? "addClass" : "removeClass"]("readOnly").prop("readOnly",readOnly);
		
		return this;
	};

	// 值处理
	$.autocomplete.prototype.value = function(value,text) {
		
		// getter method
		if (value === undefined) {return this.$hidden[0].value;}
		
		// 类似于清空效果
		value===null ? value='' : false;

		var oldValue = this.value();
		
		// 参数为数据记录或者普通字符串数据
		var index = value === '' ? -1 :  this.indexOf(value);

		var record = index != -1 ? this.records[index] : null;

		// 对应记录不存在
		if(record == null && value ){
				
			record = value;
			
			if(typeof value == 'string'){

				record={};
				record[this.valueField] = value;
				record[this.displayField] = text || value;	
				
			}

			// 创建下拉DOM
			if(!this.records.length){
				index = 0;
				this.json2Html([record]);
			}
		}

		value = record ? record[this.valueField] : '';

		text = record ? record[this.displayField] : '';
		
		this._selected_ = index;
		
		this.$hidden[0].value = value;

		var ph=this.placeholder;
		
		// placeholder样式
		this.$element[0].value = ph && text==="" ? ph : text;
		ph && this.$element[(text ? "remove" : "add") + "Class"]("placeholder");
				
		var newValue = this.value();
		
		// 触发事件
		oldValue != newValue && this.trigger("select",record);

		// 触发事件
		oldValue != newValue && this.trigger("change",newValue,oldValue);

		return this;
	};

	// 值重置
	$.autocomplete.prototype.reset = function(value,text) {
		
		this._last_query='';
		
		this._default_value= value != null && typeof value == 'object' ? value[this.valueField] : value;

		// 字符串化
		this._default_value = this._default_value === undefined ? '' : ''+this._default_value;
		
		this.value(value,text);

		return this;
	};
	
	// 添加子联动节点 
	$.autocomplete.prototype.addChild = function(child) {
		this.children=this.children || [];
		
		for(var i=0,l=this.children.length;i<l;i++)
			if(this.children[i]===child)
				break;

		l==0 || i===l ? (child.parent=this,this.children.push(child)) : false;
		return this;
	};
	
	// 删除子联动节点
	$.autocomplete.prototype.removeChild = function(child) {
		this.children=this.children || [];
		for(var i=0,l=this.children.length;i<l;i++)
			if(this.children[i]===child)
				break;
		i!==l ? (child.parent=null,this.children.splice(i,1)) : false;
		return this;
	};
	
	// 是否包含联动节点
	$.autocomplete.prototype.hasChild = function() {
		return this.children && this.children.length > 0;
	};
	
	$.autocomplete.prototype.trigger = function(event) {
		var params = [ this];
		for ( var i = 1, l = arguments.length; i < l; i++) {
			params[i] = arguments[i];
		}
		
		var type=event.toUpperCase();
		event=new jQuery.Event(type, type+"."+this.widget );
		this.$element.triggerHandler(event, params);
	
		return event;
	};

	$.autocomplete.prototype.destroy=function(keep){
		
		this.$list.off(".autocomplete").remove();
		
		this.$element.off(".autocomplete").removeData();

		this.off();
		
		var name=this.$hidden[0].name;
		
		this.$hidden.remove();
		
		!!keep ? this.$element[0].name=name : this.$element.remove();
		
	};
	
	$.autocomplete.prototype.on = function(event, handler) {
		this.$element.on(event.toUpperCase() + "." + this.widget, handler);
		return this;
	};
	
	$.autocomplete.prototype.one = function(event, handler) {
		this.$element.one(event.toUpperCase() + "." + this.widget, handler);
		return this;
	};


	$.autocomplete.prototype.off = function(event, handler) {
		this.$element.off(((event && event.toUpperCase()) || '') + "." + this.widget, handler);
		return this;
	};

	$.autocomplete.prototype.widget = 'autocomplete';
	
	$.fn.autocomplete = function(options) {
		
		var f=null,fields=[];

		for(var i=0,l=this.length;i<l;i++){
				f=$.data(this[i], "widget");
				!f ? (f=new $.autocomplete(this.eq(i), $.extend( {}, $.fn.autocomplete.defaults, options)),$.data(this[i], "widget", f)) : false;
				fields[i]=f;
		}

		return l===1 ? fields[0] : fields;
	};
	
	/**
	 * Default options for autocomplete plugin
	 */
	$.fn.autocomplete.defaults = {
		
		dataRoot:'dataroot',
		
		/** 录入最少字符 **/
		minChars : 1,

		/** 前后台交互属性 **/
		name : '',

		/** 添加class到input **/
		cls : '',

		/** 添加class到下拉列表 **/
		listCls : '',

		/** 下拉列表高度,默认auto **/
		listHeight:'',
		
		/** 下拉列表宽度,默认与文本框相同 **/
		listWidth:'force',

		/** 定时器间隔 **/
		delay : 250,

		/** 下拉条目模板 **/
		tpl : '',

		/** 显示域 **/
		displayField : 'name',

		/** 值域 **/
		valueField : 'code',

		/** 此配置在表单数据加载时有用 **/
		textField:'',
		
		/** 查询字段 **/
		queryField : '',

		/** 远程请求配置 **/
		url : '',
		urlParams : {},

		/** 发送到后台的页面大小配置 **/
		limit : 10,

		/** 本地缓存 **/
		useCache : true,
		cacheSize : 10
	};

})(jQuery);
 
    调用方式很简单:  

    <input type='text' id='remote' />  
      
    <script>  
      
  
    //后台返回JSON数据:result:{data:[{name:'男',code:'1'},{name:'女',code:'2'}]}  
    $("#remote").combobox({url:'getSexData.action',dataRoot:'result'});  
      
    </script>  
 
分享到:
评论

相关推荐

    jquery autocomplete下载.rar

    《jQuery Autocomplete 全面解析》 jQuery Autocomplete 是一个非常实用的插件,它为网页表单输入框提供了自动补全功能,极大地提升了用户体验。这个压缩包“jquery autocomplete下载.rar”包含了实现这一功能所需...

    jquery autocomplete

    **jQuery Autocomplete 知识详解** jQuery Autocomplete 是一个非常流行的 jQuery 插件,它为输入框提供了自动补全的功能,极大地提升了用户在网站上的交互体验。这个插件源自于 jQuery UI 库,但也可以单独使用。...

    jquery autocomplete dwr结合 修改Data

    标题中的“jQuery Autocomplete DWR结合 修改Data”指的是在Web开发中使用jQuery UI的Autocomplete组件与Direct Web Remoting (DWR)技术相结合,并对数据进行定制化处理的方法。jQuery Autocomplete是一个流行的UI...

    jquery autocomplete 动态补全例子有说明ajax加载

    jQuery Autocomplete是一款非常实用的JavaScript插件,它允许用户在输入框中输入文字时,根据已有的数据集动态提供补全建议。这个功能在许多Web应用中被广泛使用,如搜索框、表单输入等。在给定的“jquery ...

    JQuery autocomplete Ajax分页控件

    `jQuery autocomplete` 是jQuery UI库中的一个组件,它为输入框提供了自动完成的功能,能够根据用户输入的文本动态地从服务器获取并显示建议的匹配项。这个功能对于提高用户体验,特别是处理大量数据时,如搜索或者...

    jquery.autocomplete.js使用示例,可直接运行

    **jQuery Autocomplete.js 插件使用详解** jQuery Autocomplete.js 是一个非常实用的插件,它为HTML输入框提供了自动补全功能,极大地提升了用户体验。这个插件基于jQuery库,结合Ajax技术,能够实时从服务器获取...

    jQuery AutoComplete使用实例

    **jQuery AutoComplete 使用详解** jQuery AutoComplete 是一个非常流行的 jQuery 插件,它为输入框提供了自动补全功能,能够极大地提升用户体验。这个插件基于 jQuery 库,因此需要先引入 jQuery 才能使用。在本文...

    jquery Autocomplete 仿百度搜索 只能搜索提示

    在IT行业中,jQuery Autocomplete是一个常用的插件,用于实现类似于搜索引擎的自动补全功能。它为用户提供了方便快捷的输入体验,尤其适用于大型数据集的筛选。本项目以"jQuery Autocomplete 仿百度搜索 只能搜索...

    Jquery AutoComplete

    **jQuery AutoComplete 知识详解** `jQuery AutoComplete` 是一个非常流行的 JavaScript 库,它扩展了 jQuery UI 框架,为输入框提供自动补全功能。这个组件广泛应用于网页表单,尤其是在用户需要输入搜索关键词...

    Jquery Autocomplete 拼音首字母匹配

    1,本示例是基于微软拼音类库的jquery.autocomplete自动拼音首字母匹配搜索实现,解决了多音字匹配问题。 2,由于用了Linq查询,所以至少需要.NET Framework 3.5。 4,由于jquery匹配时的match项和result项来自不同...

    jquery.autocomplete.js资源压缩包下载

    《jQuery Autocomplete 智能联想框JS实现详解》 在网页开发中,为了提高用户体验,经常需要使用到一种功能——智能联想框。这个功能可以让用户在输入框中输入文字时,自动显示与输入内容相关的建议,就像百度搜索...

    Jquery AutoComplete组件+Ajax实现搜索框输入提示功能小记

    ### Jquery AutoComplete组件+Ajax实现搜索框输入提示功能详解 #### 前言 在当前Web应用开发中,提供良好的用户体验是至关重要的。本文主要介绍如何使用Jquery AutoComplete组件与Ajax技术来实现搜索框的实时输入...

    jquery autocomplete js 文件

    **jQuery Autocomplete 知识点详解** jQuery Autocomplete 是一个非常流行且实用的插件,它为HTML输入字段提供自动完成功能。这个插件基于 jQuery 库,使得在网页中实现类似百度搜索框那样的动态下拉建议变得简单易...

    jquery autoComplete

    **jQuery autoComplete 知识点详解** `jQuery autoComplete` 是一个基于 jQuery 库的插件,它为网页表单输入框提供了自动完成的功能。这个插件能够帮助用户在输入时快速匹配并显示预先设定的数据集,通常用于提升...

    jquery自动补全插件(jquery autocomplete)

    **jQuery AutoComplete 插件详解** jQuery AutoComplete 是一个非常流行的前端插件,它为输入框提供了自动补全的功能,极大地提升了用户在网页上的输入体验。这个插件基于 jQuery 库,因此,使用前需要先引入 ...

    jquery Autocomplete插件,搜索自动完成

    jQuery plugin: Autocomplete 参数及实例 官网:jQuery plugin: Autocomplete 此插件依赖于 jquery 1.2.6 --- jquery 1.8.3 转自:http://www.cnblogs.com/duanhuajian/p/3398904.html

    jquery autocomplete中文文档

    jquery-autocomplete搜索框自动完成的中文文档,上手快,轻便,功能强大

    Jquery AutoComplete 使用demo

    **jQuery AutoComplete 知识点详解** jQuery AutoComplete 是一个非常流行的 jQuery 插件,它为输入框提供了自动补全的功能,广泛应用于网页表单、搜索框等场景,以提高用户体验。这个插件允许开发者从本地数组或...

    jquery Autocomplete

    **jQuery Autocomplete** 是一个非常流行的JavaScript库,用于在输入框中实现自动补全功能。这个功能在网页表单中非常常见,可以极大地提升用户体验,尤其是处理大量数据时,如搜索框、地址输入等。jQuery ...

    Jquery AutoComplete的使用方法实例

    **jQuery AutoComplete 使用详解** jQuery AutoComplete 是一个非常流行的 jQuery 插件,它为输入框提供了自动补全功能,常用于搜索框、表单输入等场景,极大地提升了用户体验。本篇将详细介绍如何使用 jQuery ...

Global site tag (gtag.js) - Google Analytics