如何通过下拉菜单对OMDb API返回的影视数据进行排序?
修复OMDb搜索结果按名称排序的问题
问题根源
<option>绑定onclick事件兼容性差,且调用逻辑错误,post变量在此上下文不存在- 排序函数
orderListBy逻辑错误:错误引用未定义的post变量,排序依据应为属性名而非具体值 - 未保存API返回的原始数据,排序时无可用数据源
- 未正确调用数组排序方法
修复方案
1. 调整HTML结构
移除<option>的onclick,给<select>绑定change事件:
<select name="" id="filter"> <option value="" disabled selected>Sort</option> <option value="Alphabetical">A-Z</option> </select> <div class="post-list"> <div class="post"> <div class="post__title"></div> <p class="post__body"></p> <figure class="post__img"></figure> </div> </div>
2. 重构JavaScript逻辑
保存搜索结果数据源,实现正确排序并重新渲染:
const postListEl = document.querySelector('.post-list'); const filterSelectEl = document.getElementById('filter'); let currentPosts = []; // 存储当前搜索结果,用于排序复用 async function onSearchChange(event) { const title = event.target.value; setTimeout(() => renderPosts(title), 1000); } async function renderPosts(title) { const response = await fetch( `https://www.omdbapi.com/?apikey=67b7f307&s=${title}` ); const postsData = await response.json(); if (postsData.Search) { currentPosts = [...postsData.Search]; // 保存原始数据副本 renderPostList(currentPosts); } else { postListEl.innerHTML = '<p>No results found</p>'; } } function renderPostList(posts) { postListEl.innerHTML = posts.map(post => postHTML(post)).join(''); } function postHTML(post) { return ` <div class="post"> <div class="post__title">${post.Title}</div> <p class="post__body">${post.Year}</p> <figure class="post__img"><img src="${post.Poster}" alt="${post.Title}"></figure> </div> `; } // 通用属性排序函数:忽略大小写进行字母升序排序 function sortByProperty(property) { return (a, b) => { const valA = a[property].toLowerCase(); const valB = b[property].toLowerCase(); return valA > valB ? 1 : valA < valB ? -1 : 0; }; } // 监听排序下拉框变化 filterSelectEl.addEventListener('change', () => { if (filterSelectEl.value === 'Alphabetical' && currentPosts.length) { const sortedPosts = [...currentPosts].sort(sortByProperty('Title')); renderPostList(sortedPosts); } });
关键修复说明
- 用
currentPosts保存原始搜索结果,避免重复请求API - 替换
<option>的onclick为<select>的change事件,提升兼容性 - 排序函数统一转为小写比较,避免大小写干扰排序结果
- 创建数组副本进行排序,不修改原始数据源
内容的提问来源于stack exchange,提问作者Sub_Par_Golfer
相关产品推荐
相关产品推荐

