如何在jQuery项目中实现按名、姓筛选学生列表的搜索功能?
开发需求
- 实现搜索框的学生姓名匹配过滤功能:输入关键词后,匹配学生的名、姓字段,实时过滤并展示符合条件的学生结果,效果可参考官方演示样例
- 目前该功能实现遇到卡点,需要对应的技术指导
现有代码实现
业务交互JS代码
const apiInfo = $('.info'); const avg = (arr) => arr.reduce((acc, x) => acc + x, 0) / arr.length; const renderStudentInfo = (student, $target) => { const fullName = student.firstName + ' ' + student.lastName, average = avg(student.grades.map(grade => parseInt(grade, 10))); $target.append($(` <div class="infoB"> <img class="pPic float-left m-3" src="${student.pic}" alt="profile pic" /> <h4 class="title">${fullName}<h4> <p class="mb-1 stats">Email: ${student.email}</p> <p class="mb-1 stats">Comapny: ${student.company}</p> <p class="mb-1 stats">Skill: ${student.skill}</p> <p class="mb-1 stats">Average: ${average.toFixed(2)}%</p> <a href=# id="plus"><i class="mb-5 fa fa-plus float-right"></i></a> </div> `)); }; const init = () => { $.ajax({ url: 'https://api.hatchways.io/assessment/students', method: 'GET', }).then(({ students }) => { students.forEach((student) => { if (student.id.includes('')) { renderStudentInfo(student, apiInfo); } }); }); } init();
页面结构HTML代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" /> <link rel="stylesheet" href="style.css" /> </head> <body> <div class="input mt-5 mx-5"> <input id="nameSearch" type="text" class="form-control" placeholder="Search by name" aria-label="Search by name" aria-describedby="basic-addon1" /> </div> <div class="input mb-0 mt-2 mx-5"> <input id="tagSearch" type="text" class="form-control" placeholder="Search tags" aria-label="Search tags" aria-describedby="basic-addon1" /> </div> <div class="container mt-0"> <div class="info card scroll shadow p-3 mb-5 bg-white rounded"></div> <span class="glyphicon glyphicon-plus"></span> </div> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script> <script src="index.js"></script> </body> </html>
页面样式CSS代码
body{ background-color: rgb(243, 240, 240); } img{ border-radius: 50%; border: solid rgb(156, 148, 148) 1px; min-width: 130px; } .infoB{ border-bottom: solid grey 1px; } .stats{ color: grey; margin-left: 175px; } .title{ font-size: 50px; } .card { margin-top: 100px; } .scroll { max-height: 575px; overflow-y: auto; } .fa-plus{ color: grey; font-size: 50px; }
内容的提问来源于stack exchange,提问作者JrCoder
相关产品推荐
相关产品推荐

