search
HomeWeb Front-endJS TutorialJquery插件仿百度搜索关键字自动匹配功能_jquery

本文实例为大家分享了Jquery搜索关键字自动匹配功能的实现代码,供大家参考,具体内容如下
jQuery AutoComplete 是一个基于jQuery实现搜索关键字自动匹配提示的插件,该插件可扩展性强,表现性能优越,方便整合到自己的项目中使用;兼容IE 6.0+, FF 2+, Safari 2.0+, Opera 9.0+, and Chrome 1.0+ 等主流浏览器。

下面是具体的使用方法:

1、使用设置

首页,要把插件的js代码嵌入到你自己的项目中去。

复制代码 代码如下:

2、使用方法

为要实现自动匹配提示的 input 表单添加 AutoComplete 功能。


初始化 AutoComplete 对象,确保正确加载 DOM 对象,否则IE下的用户可能会出现错误。

复制代码 代码如下:
$('#query').autocomplete({ serviceUrl: 'service/autocomplete.ashx', // Page for processing autocomplete requests minChars: 2, // Minimum request length for triggering autocomplete delimiter: /(,|;)\s*/, // Delimiter for separating requests (a character or regex) maxHeight: 400, // Maximum height of the suggestion list, in pixels width: 300, // List width zIndex: 9999, // List's z-index deferRequestBy: 0, // Request delay (milliseconds), if you prefer not to send lots of requests while the user is typing. I usually set the delay at 300 ms. params: { country: 'Yes'}, // Additional parameters onSelect: function(data, value){ }, // Callback function, triggered if one of the suggested options is selected, lookup: ['January', 'February', 'March'] // List of suggestions for local autocomplete });

根据文本表单中的输入信息,进行关键字提示匹配。

复制代码 代码如下:
{ query:'Li', // Original request suggestions:['Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania'], // List of suggestions data:['LR','LY','LI','LT'] // Optional parameter: list of keys for suggestion options; used in callback functions. }

jQuery AutoComplete 插件支持 on/off功能,从而控制效果的开关。

复制代码 代码如下:
var ac = $('#query').autocomplete({ /*parameters*/ }); ac.disable(); ac.enable(); ac.setOptons({ zIndex: 1001 });

3、设置表现样式
最后,用div和css美化表现效果。

复制代码 代码如下:
Liberia
Libyan Arab Jamahiriya
Liechtenstein
Lithuania
.autocomplete-w1 { background:url(img/shadow.png) no-repeat bottom right; position:absolute; top:0px; left:0px; margin:6px 0 0 6px; /* IE6 fix: */ _background:none; _margin:1px 0 0 0; }.autocomplete { border:1px solid #999; background:#FFF; cursor:default; text-align:left; max-height:350px; overflow:auto; margin:-6px 6px 6px -6px; /* IE6 specific: */ _height:350px; _margin:0; _overflow-x:hidden; }.autocomplete .selected { background:#F0F0F0; }.autocomplete div { padding:2px 5px; white-space:nowrap; overflow:hidden; }.autocomplete strong { font-weight:normal; color:#3399FF; }

4、实例讲解

<html>
<head>
 <title></title>
 <style type="text/css">
 #txtKey{ width:300px;}
 </style>
 <link href="css/jquery.autocomplete.css" rel="stylesheet" type="text/css" />
 <script src="Jquery1.7.js" type="text/javascript"></script>
 <script src="js/jquery.autocomplete.js" type="text/javascript"></script>
 <script type="text/javascript">
  $(function () {
   var array = ['asp.net', 'asp.net mvc', 'wcf', 'wpf', 'win8', 'windows phone', '张东', '张熙', '张亚飞'];
   /*autocomplete函数
   (1)获取txtKey中用户输入的值(用户每输入一个字符,都会获取一次)
   (2)将获取的值和array集合中的元素进行比较,找出匹配的元素,并显示出来
   (3)会将用户选择的项添加到txtKey中*/
   /*result函数:对用户选择的结果进行操作。data参数表示用户选择的项*/
   $('#txtKey').autocomplete(array).result(function (event, data) { window.location.href = 'http://www.baidu.com/s&#63;wd=' + data + '&rsv_bp=0&ch=&tn=baidu&bar=&rsv_spt=3&ie=utf-8&rsv_sug3=6&rsv_sug=0&rsv_sug1=3&rsv_sug4=229&inputT=1458'; })
  })
 </script>
</head>
<body>
 <input id="txtKey" type="text" /><input id="Button1" type="button" value="百度一下" />
 <input id="Text1" type="text" />
</body>
</html>

实现效果如下:


以上就是关于jQuery AutoComplete使用方法介绍,通过完整示例为大家展示jQuery AutoComplete使用效果,希望对大家的学习有所帮助。

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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

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 Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)