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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor