Home >Web Front-end >JS Tutorial >JavaScript implements the auto-complete function of the search box (1)_javascript skills

JavaScript implements the auto-complete function of the search box (1)_javascript skills

PHP中文网
PHP中文网Original
2016-05-16 15:13:291627browse

In many websites that need to be searched, there will be an auto-complete search box. It is convenient for users to find the search terms they want. It helps users quickly find the results they want. This method is more friendly. So it is more It is recommended to use it.

Let me show you the renderings first:

Implementing this function requires the cooperation of the server. The client displays data obtained from the server through scripts.

Let’s look at the client’s HTML first:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>搜索词自动完成</title> 
<style type="text/css">
#search{ text-align: center; position:relative; } 
.autocomplete{ border: 1px solid #9ACCFB; background-color: white; text-align: left; } 
.autocomplete li{ list-style-type: none; } .clickable { cursor: default; } 
.highlight { background-color: #9ACCFB; } 
</style> 
<script type="text/javascript" src="jquery.js">
</script> 
<script type="text/javascript"> 
$(function(){ 
//取得div层 
var $search = $(&#39;#search&#39;); 
//取得输入框JQuery对象 
var $searchInput = $search.find(&#39;#search-text&#39;); 
//关闭浏览器提供给输入框的自动完成 
$searchInput.attr(&#39;autocomplete&#39;,&#39;off&#39;); 
//创建自动完成的下拉列表,用于显示服务器返回的数据,插入在搜索按钮的后面,等显示的时候再调整位置 
var $autocomplete = $(&#39;<div></div>&#39;) .hide() .insertAfter(&#39;#submit&#39;); 
//清空下拉列表的内容并且隐藏下拉列表区 
var clear = function(){ $autocomplete.empty().hide(); }; 
//注册事件,当输入框失去焦点的时候清空下拉列表并隐藏 
$searchInput.blur(function(){ setTimeout(clear,500); }); 
//下拉列表中高亮的项目的索引,当显示下拉列表项的时候,移动鼠标或者键盘的上下键就会移动高亮的项目,想百度搜索那样
 var selectedItem = null; 
 //timeout的ID var timeoutid = null; 
 //设置下拉项的高亮背景 
 var setSelectedItem = function(item){ 
 //更新索引变量 selectedItem = item ; 
 //按上下键是循环显示的,小于0就置成最大的值,大于最大值就置成0 
 if(selectedItem < 0){ 
 selectedItem = $autocomplete.find(&#39;li&#39;).length - 1; 
 } 
 else if(selectedItem > $autocomplete.find(&#39;li&#39;).length-1 ) { selectedItem = 0; } 
 //首先移除其他列表项的高亮背景,然后再高亮当前索引的背景 
 $autocomplete.find(&#39;li&#39;).removeClass(&#39;highlight&#39;) .eq(selectedItem).addClass(&#39;highlight&#39;); }; 
 var ajax_request = function(){ 
 //ajax服务端通信 $.ajax({ &#39;url&#39;:&#39;/test/index.jsp&#39;, 
 //服务器的地址 &#39;data&#39;:{&#39;search-text&#39;:$searchInput.val()}, 
 //参数 &#39;dataType&#39;:&#39;json&#39;, 
 //返回数据类型 &#39;type&#39;:&#39;POST&#39;, 
 //请求类型 &#39;success&#39;:function(data){ if(data.length) { 
 //遍历data,添加到自动完成区 $.each(data, function(index,term) { 
 //创建li标签,添加到下拉列表中 $(&#39;<li></li>&#39;).text(term).appendTo($autocomplete) .addClass(&#39;clickable&#39;) 
 .hover(function(){ 
 //下拉列表每一项的事件,鼠标移进去的操作 
 $(this).siblings().removeClass(&#39;highlight&#39;); 
 $(this).addClass(&#39;highlight&#39;); 
 selectedItem = index; },function(){ 
 //下拉列表每一项的事件,鼠标离开的操作 $(this).removeClass(&#39;highlight&#39;); 
 //当鼠标离开时索引置-1,当作标记 selectedItem = -1; }) .click(function(){ 
 //鼠标单击下拉列表的这一项的话,就将这一项的值添加到输入框中 $searchInput.val(term); 
 //清空并隐藏下拉列表 $autocomplete.empty().hide(); }); });
 //事件注册完毕 
 //设置下拉列表的位置,然后显示下拉列表 
 var ypos = $searchInput.position().top; 
 var xpos = $searchInput.position().left; 
 $autocomplete.css(&#39;width&#39;,$searchInput.css(&#39;width&#39;)); 
 $autocomplete.css({&#39;position&#39;:&#39;relative&#39;,&#39;left&#39;:xpos + "px",&#39;top&#39;:ypos +"px"}); 
 setSelectedItem(0); 
 //显示下拉列表 
 $autocomplete.show(); 
 } 
 } 
 }); 
 }; 
 //对输入框进行事件注册 
 $searchInput .keyup(function(event) { 
 //字母数字,退格,空格 
 if(event.keyCode > 40 || event.keyCode == 8 || event.keyCode ==32) { 
 //首先删除下拉列表中的信息 
 $autocomplete.empty().hide(); 
 clearTimeout(timeoutid); 
 timeoutid = setTimeout(ajax_request,100); 
 } 
 else if(event.keyCode == 38){ 
 //上 //selectedItem = -1 代表鼠标离开 
 if(selectedItem == -1){ 
 setSelectedItem($autocomplete.find(&#39;li&#39;).length-1); 
 } else { 
 //索引减1 setSelectedItem(selectedItem - 1); 
 } 
 event.preventDefault(); 
 } 
 else if(event.keyCode == 40) { 
 //下 //selectedItem = -1 代表鼠标离开 if(selectedItem == -1){ setSelectedItem(0); } 
 else { 
 //索引加1 setSelectedItem(selectedItem + 1); 
 } event.preventDefault(); 
 } 
 }) 
 .keypress(function(event){ //enter键 if(event.keyCode == 13) { 
 //列表为空或者鼠标离开导致当前没有索引值 if($autocomplete.find(&#39;li&#39;).length == 0 || selectedItem == -1) 
 { return; } 
 $searchInput.val($autocomplete.find(&#39;li&#39;).eq(selectedItem).text()); 
 $autocomplete.empty().hide(); event.preventDefault(); } }) .keydown(function(event){ 
 //esc键 if(event.keyCode == 27 ) { $autocomplete.empty().hide(); 
 event.preventDefault(); } }); 
 //注册窗口大小改变的事件,重新调整下拉列表的位置 
 $(window).resize(function() { 
 var ypos = $searchInput.position().top; 
 var xpos = $searchInput.position().left; 
 $autocomplete.css(&#39;width&#39;,$searchInput.css(&#39;width&#39;)); 
 $autocomplete.css({&#39;position&#39;:&#39;relative&#39;,&#39;left&#39;:xpos + "px",&#39;top&#39;:ypos +"px"}); 
 }); 
 }); 
 </script> 
 </head> 
 <body> 
 <div id = "search"> 
 <label for="search-text">请输入关键词</label>
 <input type="text" id="search-text" name="search-text" /> 
 <input type="button" id="submit" value="搜索"/> 
 </div> 
 </body> 
 </html>

For the server-side code, we choose JSP here, or you can use PHP. The server-side doesn’t matter, the key is to transmit data.

The code is as follows:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 
<% 
String []words = {"amani","abc","apple","abstract","an","bike","byebye", 
"beat","be","bing","come","cup","class","calendar","china"}; 
if(request.getParameter("search-text") != null) { 
String key = request.getParameter("search-text"); 
if(key.length() != 0){ 
String json="["; 
for(int i = 0; i < words.length; i++) { 
if(words[i].startsWith(key)){ 
json += "\""+ words[i] + "\"" + ","; 
} 
} 
json = json.substring(0,json.length()-1>0?json.length()-1:1); 
json += "]"; 
System.out.println("json:" + json); 
out.println(json); 
} 
} 
%>

The idea of ​​the whole process is actually quite clear. First, register the keyup event on the input box, and then obtain the json object through ajax in the event. After obtaining the data, create a li tag for each item of data and register a click event on the tag, so that when we click on each item, we can respond to the event. The key to keyboard navigation is to record the currently highlighted index value and adjust the background highlight based on the index value. The position of the drop-down list should be set according to the position of the input box. When the size of the browser changes, the position of the drop-down list can be adjusted at any time.

The above is the JavaScript implementation of the search box auto-complete function (1) introduced by the editor. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn