


javascript suggest effect automatic completion code sharing_javascript skills
First of all, the framework used is of course my framework mass Framework. Of course, you can also use other frameworks, such as jQuery. There is nothing complicated. As long as you understand the principle, you can do it in no time. Presumably, you will also encounter the task of building a search box in your future work.
Since I don’t have a backend, I use an object as a local database. What I want to do now is actually far more advanced than suggestion, something similar to the syntax prompts of an IDE. The current finished product has been put on github.
Okay, let’s do it. The first is the structural layer. Students who have installed FF can view the source code on the Baidu homepage. When a few letters are entered, the HTML will be dynamically generated. But no matter what, the result is that a DIV is placed below the search bar, with a table inside, and the table dynamically stores candidate words. And if the candidate words are not part of the user input, that is, the parts automatically added by JS, it will put them in a b tag and display them in bold. However, I felt that using table was too heavy-duty, so I used a ul list instead. In order to make IE6 also support the skimming color effect, I also put an a tag in it. In order to make it easier to pick words, I also added an attribute to it (a tag), which is specially used to store the vocabulary after the completion. It probably looks like this:
Look at the structure. It is actually two parts. div#search_wrapper is visible and div#suggest_wrapper is "invisible" (as long as there is no li element in it, it does not take up space and cannot be displayed). The input search box has an attribute autocomplete, which is used to turn off the prompt function that comes with the browser. Regarding data-value, this naming method is recommended by HTML5 and is used to define the data to be cached. Data-* will be placed in an object called dataset in cutting-edge browsers. For example:
data-meal-time="12:00">12:00
We can access it in the following ways:
var el= document.getElementById('Situ Zhengmei') ;
alert( el.dataset.drink );
alert( el.dataset.mealTime );
Of course, you can also directly take the innerText or textContext.
Note: Complete vocabulary = user input part auto-suggestion part. Therefore, you should not add so many things in the a tag to prevent spaces or other things from appearing, causing the retrieval to fail!
Then there is the style part, but I won’t go into details. Very simple:
#search_wrapper {
height:50px ;
}
#search{
width:300px;
}
#suggest_wrapper{
position:relative;
}
#suggest_list{
position: absolute;
z-index:100;
list-style: none;
margin:0;
padding:0;
background:#fffafa;
border:1px solid # ccc;
border-bottom:0 none;
}
#suggest_list li a{
display: block;
height:20px;
width:304px;
color: #000;
border-bottom:1px solid #ccc;
line-height:20px;
text-decoration: none;
}
#suggest_list li a:hover, .glow_suggest {
background:#ffff80;
}
Okay, let’s get to the point. Since I don't have a backend, I want to use a local object as a local database. This object is of course a JS object. The objects we traverse are usually obj.aaa.bbb.ccc. If we keep clicking in this way, in fact, every time we reach a dot number, we use a for in loop to traverse. Therefore, we monitor the input of text content, obtain the content of the input box once it changes, and then compare it in the for in loop. If it is an attribute that starts with this input value, take it out and put it into an array until you get ten. Then splice the contents of these arrays into the li element format depicted above and paste them into the ul element. Among them, we also need to pay attention to the dots. If we enter the dot number at the beginning, we will take the ten attributes of the window object. When we encounter the dot number in the future, we will switch this object.
Okay, let’s start writing code. Since my framework is used, you can go here. There is a README on the project homepage, which teaches you how to install the micro.Net server and view documents. At the beginning, you can think of it as jQuery with the module loading function added. The API is 90% similar. We need to use its event module and attribute module. It will load the relevant dependencies, add the ready parameter, and it will be executed after domReady. After we select the input box, we bind an input event to it. This is an event supported by standard browsers. My framework is already compatible under IE. Students who use jQuery and native please use the propertychange event to simulate it.
//by Situ Zhengmei
$.require( "ready,event,attr",function(){
var search = $("#search"), hash = window, prefix = "", fixIE = NaN;
search.addClass("search_target") ;
search.input(function(){//Monitor input
var
input = this.value,//Original value
val = input.slice( prefix.length),//Compare Value
output = []; //Used to place the output content
if( fixIE === input){
return //IE fix will be triggered even if the value in the input box is changed through the program The propertychange event prevents us from flipping up and down
}
for(var prop in hash){
if( prop.indexOf( val ) === 0 ){//Get the index starting with the input value API
if( output.push( '
break;
}
}
}
//If a dot is encountered forward, or a dot is canceled backwards
if( val.charAt(val.length - 1) === "." || (input && !val) ){
var arr = input.split("."); hash = window;
for(var j = 0; j var el = arr[j ];
if(el && hash[ el ]){
hash = hash[ el ];//Reset the object to traverse the API
}
}
prefix = input == "." ? "" : input;
for( prop in hash){
if( output.push( '
break;
}
}
}
$("#suggest_list").html( output.join("") );
if(!input){//Reset all
hash = window;
fixIE = prefix = output = [];
}
});
});
When the prompt list comes out, we monitor the up and down effect. That is, when you click the direction key on the keyboard, the prompted item will be highlighted up and down, and it will be filled in the search box. At this time, you need to bind the keyup event and check its keyCode. Standard browsers call it which. You can read my blog post "Javascript Keyboard Event Summary". The implementation principle is very simple. Define a peripheral variable to store the highlighted position (index value), then decrease it by one when scrolling up, and increase it by one when scrolling down. Then get all a tags in the prompt list. Use the index value to locate a certain a tag, highlight it, and then remove the originally highlighted a tag.
//by Situ Zhengmei
$.require("ready,event,attr",function(){
var search = $("#search"), hash = window, prefix = "";
search.input(function(){//Monitor input
//.....
});
var glowIndex = -1;
$(document) .keyup(function(e){//Monitor up and down
if(/search_target/i.test( e.target.className)){//Only proxy specific elements to improve performance
var upOrdown = 0
if(e.which === 38 || e.which === 104){ //up 8
upOrdown --;
}else if(e.which === 40 || e .which === 98){//down 2
upOrdown ;
}
if(upOrdown){
var list = $("#suggest_list a");
//Transfer Highlighted column
list.eq(glowIndex).removeClass("glow_suggest");
glowIndex = upOrdown;
var el = list.eq( glowIndex ).addClass("glow_suggest");
fixIE = el.attr("data-value")
search.val( fixIE )
if(glowIndex === list.length - 1){
glowIndex = -1;
}
}
}
});
});
Finally, press Enter to submit. I wrote another keyup event. Of course, you can try to combine two keyups into one (monitoring window). I wrote it this way purely for teaching purposes.
//by Situ Zhengmei
$.require( "ready,event,attr",function(){
var search = $("#search"), hash = window, prefix = "";
search.input(function(){//Listen to input
//.....
});
var glowIndex = -1;
$(window).keyup(function(e){//Listen for up and down scrolling
// .....
});
search.keyup(function(e){//Listen for submission
var input = this.value;
if(input && (e.which == 13 || e.which == 108)){ //If you press the ENTER key
alert(input)//In the actual project, the page should jump and go to the search results page }
});
});

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

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

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
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

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.
