【问题标题】:How can I generate a random selection based on user's <select> option choice?如何根据用户的 <select> 选项选择生成随机选择?
【发布时间】:2022-11-23 13:46:20
【问题描述】:

我试图让用户从我的下拉列表中选择一种类型,并从他们选择的类型中获得一个随机结果,然后显示在屏幕上。

换句话说,我的想法是让用户从他们从我的列表中选择的类型中获得随机选项。

我对 JavaScript 非常陌生,但我想尝试为我的项目做一些有创意的事情。到目前为止我已经试过了

function xyz() {
  var x = document.getElementById("selectedId").value;
  if (x == "action") {
    var action = ["Attack on Titan", "Fullmetal Alchimist", "One Punch Man", "Sword Art Online", "My Hero Academia", "Demond 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", "Parastyle", "Cowboy Bebop", "Fairy Tail", "Soul Eater", "Jojo's Bizarre Adventure", "Black Clover", "Fullmetal Alchemist", "That Time I got Reincarnated as a Slime", "Fire Force", "Balck butler", "Spy x Family", "The Seven Deadly Sins", "Tokyo Revengers", "Devilman: Crybaby", "Chainsaw Man"]
    var result = Math.floor(Math.random() * action.length);
    console.log(action);
  } else if (x == "comedy ") {
    var 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"]
    var result = Math.floor(Math.random() * comedy.length);
    console.log(comedy);
  } else if (x == "drama") {
    var drama = ["Attack on Titan", "Fullmetal Alchemist", "Your Name.", "Steins:Gate", "A Silent Voice", "Code Geass", "Toradora!", "Your Lie in Apirl", "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 Bizarren Adventure", "Classroom of the Elite", "Tokyo Revengers", "ReLIFE", "Monster", "5 Centimeters Per Second", "Plasic Memories", "Tower of God", "The Garden of Words", "Banana Fish", "Orange", "To Your Eternity", "Fruits Basket", "91 Days"]
    var result = Math.floor(Math.random() * drama.length);
    console.log(drama);
  } else if (x == "sliceofLife") {
    var 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", "Mushu-Shi", "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"]
    var result = Math.floor(Math.random() * sliceofLife.length);
    console.log(sliceofLife);
  } else if (x == "fantasy") {
    var 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 Tale", "Violet Evergrden", "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", "Demond Slayer", "That Time I Got Reincarnated as a Slime", "log Horizon", "Re:Zero", "Goblin Slayer", "Tenki no Ko", "Tower of God", "The God of High School", "GATE", "Fruits Basket", "The Asterisk War"]
    var result = Math.floor(Math.random() * fantasy.length);
    console.log(fantasy);
  } else if (x == "horror") {
    var horror = ["Tokyo Ghoul", "Parasyte", "Another", "Elfen Lied", "Highschool of the Dead", "Deadman Wonderland", "Devilman: Crybaby", "Hellsling Ultimate", "Akira", "When They Cry", "Kabaneri of the Iron Fortress", "From the New World", "Beserk", "Shiki", "Ajin", "Psprika", "Dorohedoro", "Mieruko-chan", "Blood+", "Corpse Party: Tortured Souls", "Hell Girl", "Gantz", "Danganronpa", "Mononoke", "High-Rise Invasion", "Happy Sugar Life", "Ghost Hunt", "The Los Village", "Pupa", "Ghost Stories", "Lunar Ledgen Tsukihime", "Junji Ito Collection", "Zetman", "Memories"]
    var result = Math.floor(Math.random() * horror.length);
    console.log(horror);
  } else if (x == "mystery") {
    var mystery = ["Earsed", "The Promised Neverland", "Another", "Kakegutui", "Durarara", "Hyouka", "Made in Abyss", "Bungo Stray Dog", "Black Butler", "Monster", "Darker then Black", "Black Bullet", "Tower of God", "When They Cry", "K", "From the New World", "Serial Experiments Lain", "Great Pretender", "Vanpire Knight", "Eden of The East", "No.6", "Summer Time Rendering", "Wolf's Rain", "Amnesia", "High-Rise Invation", "Astra Lost in Space"]
    var result = Math.floor(Math.random() * mystery.length);
    console.log(mystery);
  } else if (x == "psychological") {
    var psychological = ["Deaht 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 Emd", "B: The Beginning", "Invaded", "When Marnie Was There", "Tomodachi Game", "Haibane Renmei", "Death Billards", "Flowers of Evil"];
    var result = Math.floor(Math.random() * psychological.length);
    console.log(psychological);
  } else {
    var boysLove = ["Given", "No.6", "Love Stage!", "Beyond the Boundary: I'll Be Here - Future", "Junjou Romantica", "Doukyusei -Classmates-", "Hitorijimd My Hero", "Sasaki and Miyano", "Dakaretai Otoko 1-i ni Odosarete Imasu.", "Super Lovers", "Yarchin Bitch-bu", "Gakuen Heaven", "kirepapa", "Yes, No, or Maybe?", "Ten Count", "Fake"]
    var result = Math.floor(Math.random() * boysLove.length);
    console.log(boysLove);
  }
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <!--Language encoding-->
  <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>
    <p>
      <br>
    </p>

    <div class="Directory">
      <!-- Website navigation-->
      <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">
      <!--MS= format for main section-->
      <h1>Random Anime Generator</h1>
      <label> Select your Favorite genres to generate a anime!</label>
      <select id="selectedId">
        <option>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="fantsy">Fantsy</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>

【问题讨论】:

    标签: javascript html list arraylist


    【解决方案1】:

    您可以将所有完整的动漫标题列表存储在一个变量中——最好是一个数组对象。每当用户选择一种类型时,您可以简单地为每个子列表的长度生成一个随机整数,并将结果显示在目标 p 元素中。

    有关工作示例,请参见下面的 sn-p。除了删除与问题无关的元素外,我没有过多修改原始 HTML 标记。

    为了使其按预期工作,您需要确保 option 值列表与 titles 对象的键匹配。

    const titles = {
      action: ["Attack on Titan", "Fullmetal Alchimist", "One Punch Man", "Sword Art Online", "My Hero Academia", "Demond 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", "Parastyle", "Cowboy Bebop", "Fairy Tail", "Soul Eater", "Jojo's Bizarre Adventure", "Black Clover", "Fullmetal Alchemist", "That Time I got Reincarnated as a Slime", "Fire Force", "Balck 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 Apirl", "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 Bizarren Adventure", "Classroom of the Elite", "Tokyo Revengers", "ReLIFE", "Monster", "5 Centimeters Per Second", "Plasic 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", "Mushu-Shi", "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 Tale", "Violet Evergrden", "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", "Demond Slayer", "That Time I Got Reincarnated as a Slime", "log Horizon", "Re:Zero", "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", "Hellsling Ultimate", "Akira", "When They Cry", "Kabaneri of the Iron Fortress", "From the New World", "Beserk", "Shiki", "Ajin", "Psprika", "Dorohedoro", "Mieruko-chan", "Blood+", "Corpse Party: Tortured Souls", "Hell Girl", "Gantz", "Danganronpa", "Mononoke", "High-Rise Invasion", "Happy Sugar Life", "Ghost Hunt", "The Los Village", "Pupa", "Ghost Stories", "Lunar Ledgen Tsukihime", "Junji Ito Collection", "Zetman", "Memories"],
      mystery: ["Earsed", "The Promised Neverland", "Another", "Kakegutui", "Durarara", "Hyouka", "Made in Abyss", "Bungo Stray Dog", "Black Butler", "Monster", "Darker then Black", "Black Bullet", "Tower of God", "When They Cry", "K", "From the New World", "Serial Experiments Lain", "Great Pretender", "Vanpire Knight", "Eden of The East", "No.6", "Summer Time Rendering", "Wolf's Rain", "Amnesia", "High-Rise Invation", "Astra Lost in Space"],
      psychological: ["Deaht 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 Emd", "B: The Beginning", "Invaded", "When Marnie Was There", "Tomodachi Game", "Haibane Renmei", "Death Billards", "Flowers of Evil"],
      boysLove: ["Given", "No.6", "Love Stage!", "Beyond the Boundary: I'll Be Here - Future", "Junjou Romantica", "Doukyusei -Classmates-", "Hitorijimd My Hero", "Sasaki and Miyano", "Dakaretai Otoko 1-i ni Odosarete Imasu.", "Super Lovers", "Yarchin Bitch-bu", "Gakuen Heaven", "kirepapa", "Yes, No, or Maybe?", "Ten Count", "Fake"]
    }
    
    
    const selectionHandler = e => {
      const genre = e.target.value;
      const targetList = titles[genre];
      if (!targetList) {
        result.innerText = "No anime found";
      } else {
        const randomIndex = Math.floor(Math.random() * targetList.length);
        result.innerText = targetList[randomIndex];
      }
    }
    
    const input = document.querySelector('#selectedId');
    const result = document.querySelector('#result');
    input.addEventListener('change', selectionHandler);
    #result {
      padding: 10px;
      background: #eee;
      display: inline-block;
    }
    <div id="Top">
      <p class="title"> Anime for All</p>
    
      <div class="MS">
        <!--MS= format for main section-->
        <h1>Random Anime Generator</h1>
        <label> Select your Favorite genres to generate a anime!</label>
        <select id="selectedId">
          <option>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">Fantsy</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>
      </div>
    </div>

    【讨论】:

      猜你喜欢
      • 2020-02-24
      • 2020-10-13
      • 1970-01-01
      • 1970-01-01
      • 2018-04-28
      • 2022-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多