Jquery imitation search automatic association function code

  • 2020-03-30 03:03:20
  • OfStack

 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<title>Insert title here</title> 
<style type="text/css"> 
body{margin:0px;padding:0px;} 
ul{margin:px;padding:0px;list-style-type:none;} 
</style> 
<script src="jquery-1.8/jquery-1.8.0.js"></script> 
<script> 
$(function(){ 
a(); 
onclick(); 
$("#txt").bind("keyup",function(){ 
txtchange(0); 
}); 

}); 

function a(){ 
ularray=[]; 
var data=[{1:11},{1:12},{1:22},{1:33},{1:123}]; 

//Pass in data to ul
var ul=$("#ul1"); 
$.each(data,function(index,item) 
{ 
var li=$("<li></li>"); 

$.each(item,function(name,value) 
{ 
var span=$("<span></span>").html(value); 
li.append(span); 
ularray.push(value); 
}); 
ul.append(li); 
}); 

// The sorting  
ularray.sort(); 
}; 

//Keyup event
function txtchange(flag) 
{ 
var textObj=$("#txt").val(); 
var divObj=$("#div1").html(); 
var array=[]; 

with(divObj) 
{ 
var ulHTML=divObj.match(/<[^>]*>/)[0];//Get the start tag
val = ularray+ ""; //To string

for(var i=0;i<ularray.length;i++) 
{ 
if(val.split(",")[i].indexOf(textObj)!==-1||flag) //Split into an array of strings
{ 
array[array.length]="<li><span>"+ularray[i]+"</span></li>"; 
}; 
};//Put the newly acquired collection into the array

var liHtml = ""; 
$.each(array,function(item,val){ 
liHtml += val; 
});//Remove commas between arrays

divObj=ulHTML+liHtml+"</ul>"; 
$("#ul1").html(divObj); 
onclick(); //Let the new array have a click function
}; 
}; 

//Span click event
function onclick(){ 
$("#ul1 li span").click(function() 
{ 
var oli=$(this); 
var otxt=$(this).html(); 
$("#txt").empty().val(otxt); 

}); 
}; 
</script> 
</head> 

<body > 
<center> 
<form> 
<input id="txt" type="text" /> 
 Automatic prompt  
<div id="div1"> 
<ul id="ul1" > 
</ul> 
</div> 
</form> 
</center> 
</body> 
</html> 

Related articles: