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

如何基于用户<select>下拉选项生成随机动漫推荐结果?

问题分析与修正方案

你的代码存在几个关键问题导致功能无法正常工作,以下是修正后的完整代码以及问题说明:

修正后的HTML代码

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title> Final Project </title>
  <link rel="stylesheet" type="text/css" href="FPCSS.css" />
</head>

<body class="style">
  <div id="Top">
    <p class="title"> Anime for All <IMG class="IMG1" SRC="five.gif"> </p>
    <br>

    <div class="Directory">
      <h1>Directory</h1>
      <p><a href="FP1.html"> Homepage</a></p>
      <p><a href="FP2.html"> Anime History</a></p>
      <p><a href="FP3.html"> Misconceptions and Genres</a></p>
      <p><a href="FP4.html"> Recommendations</a></p>
      <p><a href="FP5.html"> Random Anime Generator</a></p>
      <p><a href="mailto:alexlearnard3436@gmail.com">Email me!</a></p>
    </div>

    <div class="MS">
      <h1>Random Anime Generator</h1>
      <label> Select your Favorite genres to generate a anime!</label>
      <select id="selectedId" onchange="xyz()">
        <option value="">Choose a Genre</option>
        <option value="action"> Action</option>
        <option value="adventure">Adventure</option>
        <option value="comedy">Comedy</option>
        <option value="drama">Drama</option>
        <option value="sliceOfLife">Slice Of Life</option>
        <option value="fantasy">Fantasy</option>
        <option value="horror">Horror</option>
        <option value="mystery">Mystery</option>
        <option value="psychological">Psychological</option>
      </select>
      <p> Your random anime based on chosen genre is....</p>
      <p id="result"> </p>
      <script src="Final_Project_JS.js"></script>
    </div>
  </div>
</body>
</html>

修正后的JavaScript代码

const animeGenres = {
  action: ["Attack on Titan", "Fullmetal Alchemist", "One Punch Man", "Sword Art Online", "My Hero Academia", "Demon Slayer", "Naruto", "Tokyo Ghoul", "Hunter x Hunter", "Code Geass", "Jujutsu Kaisen", "One Piece", "Noragami", "Akame ga Kill!", "Mob Psycho 100", "Assassination Classroom", "Blue Exorcist", "Bleach", "Parasyte", "Cowboy Bebop", "Fairy Tail", "Soul Eater", "JoJo's Bizarre Adventure", "Black Clover", "That Time I got Reincarnated as a Slime", "Fire Force", "Black Butler", "Spy x Family", "The Seven Deadly Sins", "Tokyo Revengers", "Devilman: Crybaby", "Chainsaw Man"],
  comedy: ["One Punch Man", "No Game NO Life", "Mob Psycho 100", "Assassination Classroom", "KonoSuba: God's Blessing on This Wonderful World!", "Kill la Kill", "Rascal Does Not Dream of Bunny Girl Senpai", "Dr.Stone", "Kaguya-sama: Love is War", "Soul Eater", "Gurren Lagann", "The Devil is a Part-Timer", "Black Clover", "High School DxD", "That Time I Got Reincarnated as a Slime", "Maid Sama!", "Spy x Family", "Black Butler", "Nisekoi", "Ouran High School Host Club", "My Little Monster", "JoJo's Bizarre Adventure", "K-On!", "The Disastrous Life of Saiki K.", "My Teen Romantic Comedy SNAFU TOO!", "Golden Time", "Monthly Girls' Nozaki-kun", "Rent-a-Girlfriend", "The Quintessential Quintuplets", "Don't Toy with Me, Miss Nagatoro", "How Not to Summon a Demon Lord", "Ghost Stories"],
  drama: ["Attack on Titan", "Fullmetal Alchemist", "Your Name.", "Steins:Gate", "A Silent Voice", "Code Geass", "Toradora!", "Your Lie in April", "Re:Zero", "Angel Beats!", "Death Parade", "Violet Evergarden", "Rascal Does Not Dream of Bunny Girl Senpai", "Anohana: The Flower We Saw That Day", "Clannad", "Charlotte", "Kakegurui", "Made in Abyss", "The Pet Girl of Sakurasou", "Guilty Crown", "JoJo's Bizarre Adventure", "Classroom of the Elite", "Tokyo Revengers", "ReLIFE", "Monster", "5 Centimeters Per Second", "Plastic Memories", "Tower of God", "The Garden of Words", "Banana Fish", "Orange", "To Your Eternity", "Fruits Basket", "91 Days"],
  sliceOfLife: ["Violet Evergarden", "Anohana: The Flower We Saw That Day", "Hyouka", "Miss Kobayashi's Dragon Maid", "ReLIFE", "5 Centimeters Per Second", "The Melancholy of Haruhi Suzumiya", "Blue Spring Ride", "Kimi ni Todoke: From Me to You", "I Want To Eat Your Pancreas", "My Dress-Up Darling", "The Garden of Words", "Beastars", "Mushishi", "Wolf Children", "Nana", "Barakamon", "Natsume's Book of Friends", "Bunny Drop", "Laid-Back Camp", "Love-Live!", "Tanaka-Kun is Always Listless", "Kimi ni Todoke", "School-Live!", "Tamako Market", "Beck", "Place to Place", "One Week Friends", "Girls' Last Tour", "Remake Our Life!", "Silver Spoon", "Flying Witch", "Doukyusei-Classmates", "Colorful"],
  fantasy: ["Sword Art Online", "Demon Slayer", "Naruto", "Tokyo Ghoul", "Hunter x Hunter", "No Game No Life", "Jujutsu Kaisen", "One Piece", "Noragami", "Re:Zero", "Akame ga Kill!", "The Seven Deadly Sins", "Bleach", "Blue Exorcist", "Fairy Tail", "Violet Evergarden", "Soul Eater", "The Devil is a Part-Timer!", "Black Clover", "Overlord", "The Rising of the Shield Hero", "Is it Wrong to Try to Pick Up Girls in a Dungeon", "fate/Zero", "Noragami Aragoto", "That Time I Got Reincarnated as a Slime", "Log Horizon", "Goblin Slayer", "Tenki no Ko", "Tower of God", "The God of High School", "GATE", "Fruits Basket", "The Asterisk War"],
  horror: ["Tokyo Ghoul", "Parasyte", "Another", "Elfen Lied", "Highschool of the Dead", "Deadman Wonderland", "Devilman: Crybaby", "Hellsing Ultimate", "Akira", "When They Cry", "Kabaneri of the Iron Fortress", "From the New World", "Berserk", "Shiki", "Ajin", "Paprika", "Dorohedoro", "Mieruko-chan", "Blood+", "Corpse Party: Tortured Souls", "Hell Girl", "Gantz", "Danganronpa", "Mononoke", "High-Rise Invasion", "Happy Sugar Life", "Ghost Hunt", "The Lost Village", "Pupa", "Ghost Stories", "Lunar Legend Tsukihime", "Junji Ito Collection", "Zetman", "Memories"],
  mystery: ["Erased", "The Promised Neverland", "Another", "Kakegurui", "Durarara!!", "Hyouka", "Made in Abyss", "Bungo Stray Dogs", "Black Butler", "Monster", "Darker than Black", "Black Bullet", "Tower of God", "When They Cry", "K", "From the New World", "Serial Experiments Lain", "Great Pretender", "Vampire Knight", "Eden of The East", "No.6", "Summer Time Rendering", "Wolf's Rain", "Amnesia", "High-Rise Invasion", "Astra Lost in Space"],
  psychological: ["Death Note", "Tokyo Ghoul", "Re:Zero", "Erased", "The Future Diary", "The Promised Neverland", "Psycho-Pass", "Terror in Resonance", "Classroom of the Elite", "Btooom!", "FLCL", "Perfect Blue", "Ergo Proxy", "The Fruit of Grisaia", "Shiki", "Blast of Tempest", "Paranoia Agent", "Cyberpunk: Edgerunners", "Moriarty the Patriot", "Platinum End", "B: The Beginning", "ID: Invaded", "When Marnie Was There", "Tomodachi Game", "Haibane Renmei", "Death Billiards", "Flowers of Evil"],
  boysLove: ["Given", "No.6", "Love Stage!", "Beyond the Boundary: I'll Be Here - Future", "Junjou Romantica", "Doukyusei -Classmates-", "Hitorijime My Hero", "Sasaki and Miyano", "Dakaretai Otoko 1-i ni Odosarete Imasu.", "Super Lovers", "Yarichin Bitch-bu", "Gakuen Heaven", "Kirepapa", "Yes, No, or Maybe?", "Ten Count", "Fake"]
};

function xyz() {
  const genre = document.getElementById("selectedId").value;
  const resultElement = document.getElementById("result");

  if (!genre) {
    resultElement.textContent = "请先选择一个动漫类型";
    return;
  }

  const animeList = animeGenres[genre] || animeGenres.boysLove;
  const randomIndex = Math.floor(Math.random() * animeList.length);
  const randomAnime = animeList[randomIndex];

  resultElement.textContent = randomAnime;
  console.log(randomAnime);
}

关键问题说明与改进点

  1. 函数未触发:原HTML的<select>没有绑定触发函数,添加onchange="xyz()"后,选择类型时会自动执行生成逻辑。
  2. 字符串匹配错误:
    • 原JS中x == "comedy "多了空格,和HTML中value="comedy"不匹配,修正后统一为"comedy";
    • HTML中sliceOfLife的大小写和原JS中sliceofLife不一致,修正为统一的驼峰命名;
    • HTML中fantsy拼写错误,修正为fantasy。
  3. 随机值未正确使用:原代码生成了随机索引但未用它获取具体动漫,反而打印整个数组,修正后通过animeList[randomIndex]获取随机动漫并展示到页面。
  4. 数据结构优化:用对象animeGenres替代大量if-else,代码更简洁易维护,后续添加新类型只需在对象中新增属性即可。
  5. 边界情况处理:添加了未选择类型时的提示,以及对未定义类型(比如HTML中的adventure)的 fallback 处理,避免报错。
  6. 拼写错误修正:修正了数组中诸如Demond Slayer→Demon Slayer、Plasic Memories→Plastic Memories等拼写问题,提升数据准确性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 13:05:43