步驟:
1.傳入兩個參數,第一個是你要綁定的表單對象,第二個是你要檢索的數組.
2.動態(tài)建立一個div做為你要自動完成的層,設置屬性和事件(我在這里并沒有設置div的visible和display屬性,而是將它的left設為"-1000px",這樣就移出了瀏覽器之外,達到了隱藏的效果.
3.對傳入的數組進行檢索,找出與輸入內容匹配或相近的項,并將其存入一個新的數組.這里用正則表達式進行了四次迭代,寫的不好,還望見諒.
4.對存入檢索后數據的那個新數組進行處理,去掉內容重復的項,并將其寫進div內.
5.設置div的left,top,width即可.
下面看給出的完整代碼: 聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com
代碼如下:
if(!sx)
var sx={};
sx.activex={};
sx.activex.autocomplete={
bind:function(a,s){
var d=document.createElement("div");
d.style.position="absolute";
d.flag="autocomplete";
document.body.appendChild(d);
d.style.left="-1000px";
d.style.height="100px";
d.style.overflow="auto";
a.onblur=function(){
if(document.elementFromPoint(window.event.clientX,window.event.clientY).flag=="autocomplete" || document.elementFromPoint(window.event.clientX,window.event.clientY).parentNode.flag=="autocomplete")
return;
d.innerHTML="";
d.style.left="-1000px";
}
a.onkeyup=function(){
if(a.value=="") {
d.innerHTML="";
return;
}
d.innerHTML="";
var t=[];
for(var i in s){
if(eval("/^"+a.value+"$/i").test(s[i])){
t.push(s[i]);
}
}
for(var i in s){
if(eval("/^"+a.value+".+$/i").test(s[i])){
t.push(s[i]);
}
}
for(var i in s){
if(eval("/^.+"+a.value+"$/i").test(s[i])){
t.push(s[i]);
}
}
for(var i in s){
if(eval("/^.+"+a.value+".+$/i").test(s[i])){
t.push(s[i]);
}
}
for(var e=0;e<=t.length-2;e++){
for(var e1=e+1;e1<=t.length-1;e1++){
if(t[e]==t[e1]){
for(var e2=e1+1;e2
t[e2-1]=t[e2];
}
}
t.length=t.length-1;
}
}
}
//alert(t);
for(var i in t){
var p=document.createElement("div");
p.innerText=t[i];
p.onmouseenter=function(){
this.style.backgroundColor="blue";
}
p.onmouseleave=function(){
this.style.backgroundColor="white";
}
p.onclick=function(){
a.value=this.innerText;
d.style.left="-1000px";
}
d.appendChild(p)
}
d.style.top=a.offsetTop+a.offsetHeight+"px";
d.style.left=a.offsetLeft+"px";
d.style.width=a.offsetWidth+"px";
}
}
}.
調用的html代碼:
代碼如下: