做网页方面的程序,经常需要用到文本框的自动补全功能,在网上找了一个ajax的autoComplete,还挺好用的。实现的功能是:在文本框输入文本,搜索数据库文本关键字自动补全文本框。
1、autoComplete的代码(其实是个js文件),(注:该代码是在csdn论坛找到的,代码内又原作者信息)
/*
*Author:sohighthesky
*From:http://blog.csdn.net/sohighthesky
*Date:2009-11-14
*/
/*
*textbox 指定要显示自动完成的方本框
*options:参见代码中setOptions中的注释
*/
var autoComplete=function(textbox,options) {
this.textbox=this.g(textbox);
this.setOptions(options);
this.init();
}
autoComplete.prototype={
g:function(id) {return typeof(id)=="string"?document.getElementById(id):id;},
ae:function(el,type,call) {
if(el.addEventListener)el.addEventListener(type,call,false);
else el.attachEvent("on"+type,call);
},
getPos:function(){//取元素坐标
var o=this.textbox;
var x = 0, y = 0;
do{x += o.offsetLeft; y += o.offsetTop;}
while(o=o.offsetParent);
return {'x':x,'y':y};
},
setOptions:function(options) {
this.options={
url:"search.ashx",//指定页面
urlstr:"keyword",//指定url参数
suggestAppend:true,//是否在选择时将值添加到文本框
isTextboxWidth:false,//默认使用样式表中的宽度,设置为true时,显示与文本框一样的宽度
beforeSubmit:function(val,textbox){},//返回false不提交,
submitBtn:null//指定要提交的按钮
};
for(var o in options) {this.options[o]=options[o];}
},
initxhr:function() {
this.xhr=false;
if(window.XMLHttpRequest) {
this.xhr=new XMLHttpRequest();// for IE7/+,Firefox,Opera,Chorme,Safari
} else {
try {this.xhr=new ActiveXObject("Msxml2.XMLHTTP");/*IE6+*/ } catch(ex) {}
}
},
ajax:function(){
var o=this;
if(!o.xhr)return;
try {o.xhr.abort();}catch(ex){}
o.xhr.onreadystatechange=function(){
if(o.xhr.readyState==4 &am