You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

电影网站JavaScript分类筛选与搜索功能异常问题求助

故障修复方案

两个核心问题说明

  • 剧情分类点击无响应:代码中绑定剧情分类的点击事件时,错误把监听器绑到了动作分类的DOM对象上,点击剧情分类不会触发对应筛选逻辑
  • 分类筛选后搜索失效:搜索逻辑直接修改元素display属性,分类筛选用active/inactive类控制显隐,两个控制逻辑优先级冲突,导致搜索修改的样式被分类样式覆盖

修复后的完整JavaScript代码

// jshint esversion:6
const selected = document.querySelector(".selected");
const optionsContainer = document.querySelector(".option-container");
const optionList = document.querySelectorAll(".option");
// 全局存储当前选中的分类,方便搜索时联动筛选
let currentCategory = 'all';

selected.addEventListener("click", clickable);
function clickable() {
  optionsContainer.classList.toggle("active");
}

optionList.forEach(o => {
  o.addEventListener("click", function() {
    selected.innerHTML = o.querySelector("label").innerHTML;
    optionsContainer.classList.remove("active");
  });
});

// 搜索逻辑,联动当前选中的分类
const searchBar = document.forms['search-books'].querySelector('input');
searchBar.addEventListener("keyup", function(e) {
  const term = e.target.value.toLowerCase();
  const movies = document.querySelectorAll('.allMovie');
  movies.forEach(movie => {
    const title = movie.querySelector('h4').textContent.toLowerCase();
    const titleMatch = title.indexOf(term) !== -1;
    // 同时匹配分类和搜索关键词
    let categoryMatch = true;
    if(currentCategory === 'action') categoryMatch = movie.classList.contains('actionMovie');
    if(currentCategory === 'drama') categoryMatch = movie.classList.contains('dramaMovie');
    if(currentCategory === 'sci-fi') categoryMatch = movie.classList.contains('sciFiMovie');
    // 两个条件都满足才显示
    movie.style.display = (titleMatch && categoryMatch) ? 'flex' : 'none';
  });
});

// 分类筛选逻辑,统一重写避免状态混乱
const allMovies = document.querySelector("#all");
allMovies.addEventListener("click", function () {
  currentCategory = 'all';
  // 触发一次搜索更新显示结果
  searchBar.dispatchEvent(new Event('keyup'));
});

const actionMovie = document.querySelector("#action");
actionMovie.addEventListener("click", function () {
  currentCategory = 'action';
  searchBar.dispatchEvent(new Event('keyup'));
});

const dramaMovie = document.querySelector("#drama");
dramaMovie.addEventListener("click", function () {
  currentCategory = 'drama';
  searchBar.dispatchEvent(new Event('keyup'));
});

// 科幻分类逻辑补全,需要给对应科幻电影DOM加上sciFiMovie类名即可生效
const sciFiMovie = document.querySelector("#sci-fi");
sciFiMovie.addEventListener("click", function () {
  currentCategory = 'sci-fi';
  searchBar.dispatchEvent(new Event('keyup'));
});

补充说明

原来的toggle控制类名的方式容易出现状态叠加错误,改为用全局变量记录当前选中分类,搜索时同时匹配分类和关键词,两个逻辑完全联动不会冲突,后续新增分类只需要复制对应分类的事件逻辑,给对应影片加上分类类名即可。

内容的提问来源于stack exchange,提问作者Shagun Raghav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 07:45:02