search
HomeWeb Front-endJS Tutorialjquery simulation search box automatically completes the search prompt function (improved)_jquery

autopoint.js code:

Copy code The code is as follows:

/*
* @date: 2010-5-22 21:42:15
* @author: 胡灵伟
* Depends:
* jquery.js
*
* function:类似GOOGLE搜索框提示功能
*/
(function($) {
$.fn.autopoint = function (options) {
defaults = {
url:options.url,
keyLeft : 37,//向左方向键
keyUp : 38,//向上方向键
keyRight : 39,//向右方向键
keyDown : 40,//向下方向键
keyEnter : 13,//回车键
listHoverCSS : 'jhover',//提示框列表鼠标悬浮的样式
tpl : '
{word}
约{view}条记录
',
topoffset:options.topoffset||5
};
var options = $.extend(defaults, options);
var dropDiv = $('
').addClass('dropDiv').appendTo('body');
var isOver = false;
dropDiv.hover(function(){
isOver = true;
}, 함수 (){
isOver = false;
});
return this.each(function(){
var pa = $(this);
$(this).bind(' keydown', function(event){
if (dropDiv.css('display') != 'none') {//키보드 이벤트는 프롬프트 레이어가 표시될 때만 처리됩니다.
var currentList = dropDiv.find ( '.' options.listHoverCSS);
if (event.keyCode == options.keyDown) {//아래쪽 화살표 키를 누른 경우
if (currentList.length == 0) {
/ /프롬프트 목록에서 선택된 항목이 없으면 목록에서 첫 번째 항목을 선택하세요.
$(this).val(getPointWord(dropDiv.find('.list:first')
.mouseover())) ;
} else if (currentList.next().length == 0) {
//마지막 항목이 선택되어 있으면 선택을 취소하세요. 이는 입력 상자가 선택되었음을 의미합니다.
unHoverAll(); 🎜>} else {
unHoverAll();
//원래 선택한 열의 다음 열을 선택합니다
if (currentList.next().length != 0)
$(this). val (getPointWord(currentList.next()
.mouseover()));
}
return false
} else if (event.keyCode == options.keyUp) {//눌린 경우 위쪽 화살표 키입니다
if (currentList.length == 0) {
$(this).val(getPointWord(dropDiv.find('.list:last')
.mouseover()) );
} else if (currentList.prev().length == 0) {
unHoverAll()
} else {
unHoverAll()
if (currentList.prev() ). 길이 != 0)
$(this).val(getPointWord(currentList.prev()
.mouseover()))
}
return false; (event .keyCode == options.keyEnter) dropDiv.empty().hide();
}
//키를 누르기 전에 입력 상자 값을 기록하여 키를 눌렀을 때 값이 변경되었는지 쉽게 확인할 수 있습니다. 팝업
$(this).attr('alt', $(this).val())
}).bind('keyup', function(event){
//If the 튀어나온 키는 위쪽 또는 아래쪽 화살표 키입니다. return
if(event.keyCode == options.keyDown||event.keyCode == options.keyUp) return
if($(this).val() == ' '){
dropDiv.empty().hide();
return;
}
//입력 상자 값이 변경되지 않거나 비어 있으면
을 반환합니다($ (this ).val() == $(this).attr('alt'))
return;
getData(pa, $(this).val())
}).bind (' Blur', function(){
if(isOver&&dropDiv.find('.' options.listHoverCSS)!=0) return;
//텍스트 입력 상자가 포커스를 잃으면 지워지고 프롬프트 레이어가 숨겨집니다
dropDiv.empty().hide();
})
/**Ajax 반환 성공을 처리하는 방법**/
handleResponse = function(parent, json) {
var isEmpty = true;
for( var o in json){
if(o == 'data') isEmpty = false;
}
if(isEmpty) {
showError(" 반환된 데이터 형식이 잘못되었습니다. 요청 URL이 올바른지 확인하세요!");
return;
}
if(json['data'].length == 0) {
/ /반환 데이터가 비어 있습니다
return
}
refreshDropDiv(parent, json)
dropDiv.show()
/**Ajax 실패를 처리하는 방법**/
handleError = function(error) {
//showError ("URL 오류 또는 시간 초과로 인해 요청이 실패했습니다!")
}
showError = function(error){
alert(error );
}
/**dom을 생성하는 데 사용되는 문자열을 생성하기 위해 ajax를 통해 json 형식 데이터를 반환합니다**/
render = function(parent, json) {
var res = json['data'] || varappendStr = ''
//템플릿 문자를 json 객체의 콘텐츠로 대체 콘텐츠 일치 /{([a-z] )}/ig 예: {word}, ​​​​{view}
( var i = 0; i appendStr = options.tpl.replace(/{([a-z] )}/ig, function(m, n) {
return res[i][n];
});
}
jebind(parent,appendStr)
/**새 DOM 객체를 프롬프트 상자에 삽입하고 마우스오버 이벤트 리스너를 다시 바인딩합니다**/
jebind = 함수 (부모, a) {
dropDiv.append(a);
dropDiv.find ('.list').each(function() {
$(this).unbind('mouseover'). mouseover(function() {
unHoverAll();
$(this).addClass (options.listHoverCSS);
}).unbind('click').click(function(){
parent.val(getPointWord($(this))));
dropDiv.empty().
parent.focus()
}); >}
/**프롬프트 상자의 모든 열에서 호버 스타일을 제거합니다**/
unHoverAll = function() {
dropDiv.find('.list').each(function() {
$(this).removeClass (options.listHoverCSS);
})
}
/**프롬프트 상자에서 현재 선택된 프롬프트 키워드를 가져옵니다**/
getPointWord = function(p) {
return p.find('div:first' ).text()
}
/**프롬프트 상자를 새로 고치고 스타일을 설정하세요**/
RefreshDropDiv = function(parent, json) {
var left = parent.offset().left
var; height = parent.height();
var top = parent.offset().top options.topoffset height;
var width = options.width() 'px'; .empty();
dropDiv.css( {
'border' : '1px solid #FE00DF',
'left' : 왼쪽,
'top' : 상단,
'너비 ' : width
});
render(parent, json);
/ /Ajax가 반환되기 전에 입력 상자가 포커스를 잃어 프롬프트 상자가 사라지지 않도록 방지
parent.focus() ;
}
/**ajax*를 통해 서버에서 데이터 요청*/
getData = function(parent, word) {
$.ajax( {
type : 'GET',
data : "word=" word,
url : options.url,
dataType : 'json',
timeout : 1000,
success : function(json){handleResponse(parent, json);},
오류 : handlerError
})
}
}; 🎜>
The code is as follows:




Call method :




Copy code


The code is as follows:



   


Main part of the servlet:




Copy code


The code is as follows:

response.setContentType("text/html");
response.setHeader("Cache-Control", "no-cache");
response.setCharacterEncoding("UTF-8");
String word = request.getParameter("word"); if(Utils.isBlank(word)) return; JSONObject json = new JSONObject(); JSONArray array = new JSONArray(); Map map1 = new HashMapmap1.put("word", word "a1"); map1.put("view", 10);
Map map2 = new HashMap();
map2.put("word", word "a2");
map2.put("view", 15);
Map map3 = new HashMap< ;String, Object>();
map3.put("word", word "a3");
map3.put("view", 2);
array.add(JSONObject.fromObject( map1));
array.add(JSONObject.fromObject(map2));
array.add(JSONObject.fromObject(map3));
json.put("data", array);
PrintWriter out = response.getWriter();
out.print(json.toString());
out.close();


where JSONObject and JSONArray classes come from json- lib.jar, for the convenience of testing, returns data directly. In actual applications, it can be replaced by
to retrieve data from the data source.
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
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

How do I install JavaScript?How do I install JavaScript?Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

How to send notifications before a task starts in Quartz?How to send notifications before a task starts in Quartz?Apr 04, 2025 pm 09:24 PM

How to send task notifications in Quartz In advance When using the Quartz timer to schedule a task, the execution time of the task is set by the cron expression. Now...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment