如何在HTML中实现搜索栏查询JSON文件并展示对象关联信息
实现方案
1. 核心逻辑说明
- 先准备结构化的JSON数据源,存储所有要展示的对象属性
- 新增悬浮搜索结果弹窗容器,默认隐藏
- 替换原有的
onkeyup为input事件,实现全场景实时输入监听 - 搜索匹配时遍历JSON数据,匹配到的结果动态渲染到弹窗中,支持展示所有自定义属性
2. 完整实现代码
2.1 HTML 部分
<!-- 搜索框父容器需加position: relative保证弹窗定位正确 --> <div style="position: relative;"> <input id="searchbar" type="text" name="search" placeholder="搜索动物"> <!-- 搜索结果弹窗容器 --> <div id="searchResultPopup" class="search-popup"></div> </div>
2.2 CSS 部分(实现弹窗效果)
#searchbar { padding: 8px 12px; width: 300px; } .search-popup { display: none; position: absolute; top: calc(100% + 5px); left: 0; width: 100%; max-height: 300px; overflow-y: auto; border: 1px solid #eee; border-radius: 4px; background: #fff; box-shadow: 0 2px 8px rgba(0,0,0,0.1); z-index: 999; } .search-popup .result-item { padding: 10px 15px; border-bottom: 1px solid #f5f5f5; cursor: pointer; } .search-popup .result-item:last-child { border-bottom: none; } .search-popup .result-item:hover { background: #f8f9fa; } .search-popup .result-item .attr { font-size: 12px; color: #666; margin-top: 4px; }
2.3 JS 部分
// 示例JSON数据,可替换为fetch请求的外部json文件内容 const animalData = [ { name: "大熊猫", species: "熊科", age: 5, habitat: "四川卧龙自然保护区", status: "国家一级保护动物" }, { name: "金丝猴", species: "猴科", age: 3, habitat: "陕西秦岭", status: "国家一级保护动物" }, { name: "扬子鳄", species: "鼍科", age: 12, habitat: "长江中下游流域", status: "国家一级保护动物" } ]; const searchInput = document.getElementById('searchbar'); const resultPopup = document.getElementById('searchResultPopup'); // 实时监听输入 searchInput.addEventListener('input', searchAnimal); // 点击页面其他地方隐藏弹窗 document.addEventListener('click', (e) => { if (!searchInput.contains(e.target) && !resultPopup.contains(e.target)) { resultPopup.style.display = 'none'; } }); function searchAnimal() { const inputVal = searchInput.value.trim().toLowerCase(); // 输入为空时隐藏弹窗 if (!inputVal) { resultPopup.style.display = 'none'; return; } // 匹配JSON数据,可自定义匹配的字段范围 const matchedResults = animalData.filter(item => { return Object.values(item).some(val => val.toString().toLowerCase().includes(inputVal) ); }); // 渲染结果到弹窗 if (matchedResults.length > 0) { resultPopup.innerHTML = matchedResults.map(item => ` <div class="result-item"> <div class="name">${item.name}</div> <div class="attr"> 物种:${item.species} | 年龄:${item.age}岁 | 栖息地:${item.habitat} | 保护等级:${item.status} </div> </div> `).join(''); resultPopup.style.display = 'block'; } else { resultPopup.innerHTML = '<div class="result-item">暂无匹配结果</div>'; resultPopup.style.display = 'block'; } }
3. 功能说明
- 实时弹窗:输入框每输入一个字符就会触发搜索,匹配到的结果直接在下方悬浮弹窗展示,输入为空时自动隐藏
- 多属性展示:JSON中存储的所有属性都可以自定义渲染到结果项中,不需要依赖原有DOM的innerHTML内容
- 模糊匹配:支持匹配所有字段内容,比如搜"熊科"也能匹配到大熊猫的结果
- 加载外部JSON文件的话,直接用
fetch请求对应JSON文件地址,替换animalData的内容即可
内容的提问来源于stack exchange,提问作者MyNameIsYourMother
相关产品推荐
相关产品推荐

