


Code sharing for JavaScript to implement front-end real-time search function (picture)
这篇文章主要为大家详细介绍了JavaScript实现前端实时搜索功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
大部分页面都具备搜索功能。而作为前端,我们的目的只是将用户输入的内容返回给后台而后呈现反馈数据给用户,具体实现如下:
1.基本布局:
<p class="searcher"> <p class="searcher-main"> <i><img src="/static/imghwm/default1.png" data-src="img/icon/icon-search-map.png" class="lazy" / alt="Code sharing for JavaScript to implement front-end real-time search function (picture)" ></i> <input class="searcher-text" placeholder="请输入档口名称"></input> </p> <p class="searcher-cancel">取消</p> </p>
这里涉及一个问题如何将搜索图标放入input中,网上有相关资料不做赘述:
.searcher { background: rgba(255, 255, 255, 0); position: fixed; z-index: 999; width: 100%; height: 6rem; text-align: center; font-size: 1.6rem; } .searcher-main { background: #F4F4F4; position: absolute; left: 50%; top: 1.2rem; margin-left: -45%; border-radius: 1.6rem; width: 80%; height: 3rem; line-height: 3rem; } .searcher-text { width: 80%; text-align: center; border: none; outline: none; background: #F4F4F4; } .searcher-cancel { position: absolute; width: 10%; height: 3rem; line-height: 3rem; color: #929292; top: 1.2rem; right: 1rem; }
2.step-1:
3.js部分
这里要安利IE9以上的oninput事件
onchange事件只在键盘或者鼠标操作改变对象属性,且失去焦点时触发,脚本触发无效。
onkeydown/onkeypress/onkeyup在处理复制、粘贴、拖拽、长按键(按住键盘不放)等细节上并不完善。
onpropertychange不用考虑是否失去焦点,不管js操作还是键盘鼠标手动操作,只要HTML元素属性发生改变即可立即捕获到。遗憾的是,onpropertychange为IE专属的。
//监听input框,实时渲染 $('.searcher-text').on('input', function() { initSearchList(); });
JQ一般都是用这种+=html的方法,虽然累赘不过通过url或者tag标签里属性传参较容易理解。
//渲染搜索列表 function initSearchList() { var List = $('.searcher-land ul'); var params = {}; //搜索过滤字符 var SEARCH_KEY = $('.searcher-text').val() params['action'] = 'get_search_key_list'; params['market_iid'] = 1001; params['search_type'] = TYPE; params['search_key'] = replaceIllegalStr(SEARCH_KEY); epm.ajax(params, function(result) { console.log(result); console.log(TYPE) var html = ''; List.html(''); //有结果 if(result.data.length > 0) { $.each(result.data, function(index, value) { goodName = value['goods_name']; shopName = value['shop_name']; //判断Name类型 itemName = (goodName) ? goodName : shopName; html += '<li class="goods-list">' + itemName + '</li>' }); $('.searcher-list').html(html); } //无结果 else { html = '<p class="no-goods">暂时无法找到此选项~</p>'; $('.searcher-list').html(html); } }); }
注意这里有一个replaceIllegalStr()方法,类似正则,目的是过滤掉一些无用的符号以免给后端接收数据带来不必要的麻烦。
function replaceIllegalStr(str) { var reg; var illegal_list = ["/", "\\", "[", "]", "{", "}", "<", ">", "<", ">", "「", "」", ":", ";", "、", "•", "^", "'", "\"", "\r", "\r\n", "\\n", "\n"]; for (var i = 0; i < illegal_list.length; i++) { if (str.indexOf(illegal_list[i]) >= 0) { if (illegal_list[i] == '\\' || illegal_list[i] == '[') { reg = new RegExp('\\' + illegal_list[i], "g"); } else { reg = new RegExp(illegal_list[i], "g"); } str = str.replace(reg, ''); } } return str.trim(); }
4.step-2:
5.缓存
这里我们将点击的数据保存在本地缓存里,供取用呈现:
注: epm是自己封装的一个方法与属性的对象
//设置缓存 epm.setLocalItem = function(key, value) { if (window.localStorage) { localStorage.setItem(key, value); } else { //后备方案 setCookie(key, value); } };
//提取缓存 epm.getLocalItem = function(key) { if (window.localStorage) { return localStorage.getItem(key); } else { //后备方案 return getCookie(key); } };
//删除缓存 epm.removeLocalItem = function(key) { if (window.localStorage) { localStorage.removeItem(key); } else { //后备方案 removeCookie(key); } };
6.step-3
得到点击的相应的缓存词里的value,再次发送ajax:
The above is the detailed content of Code sharing for JavaScript to implement front-end real-time search function (picture). For more information, please follow other related articles on the PHP Chinese website!

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.

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 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 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 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.

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.

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.

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.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 English version
Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool