如何让我的 HTML 输入被我的 JavaScript 函数使用?

How to let my HTML input be used by my JavaScript function?

所以我用我的 JavaScript 设置了很多对象,一个 HTML 下拉列表这样你就可以 select 哪个宠物小精灵

如您所见,我试图通过在下拉列表值为 'bulbasaur' 的列表上使用 document.getElementById 来访问 'bulbasaur' 对象。当我执行 console.log(mon) 时,它会打印 'bulbasaur' 所以我猜我无法通过这种方式访问​​对象。有解决方法吗?谢谢

const base =10;
class Pokemon {
  constructor(name, shinyrate) {
    this.name = name;
    this.shinyrate = shinyrate;
  }
}
const bulbasaur = new Pokemon('Bulbasaur', base);

function shundoWild() {
  let mon = document.getElementById("list").value;
  let nowb = mon.shinyrate * ivCombinations(ivFloor.wild);
  let wb = mon.shinyrate * ivCombinations(ivFloor.weatherBoost);
  document.getElementById("print").innerHTML = ("The chance to get a SHUNDO " + mon.name + " wild catch is ~1/" + wb + " when weather boosted, or ~1/" + nowb + " when not weather boosted.")
}
<select id="list" onchange="shundoWild();">
  <option value="bulbasaur">Bulbasaur</option>
  <option value="ekans">Ekans</option>
</select>

您可以将您的神奇宝贝枚举到一个对象结构中并按如下方式访问它:

const base =10;
class Pokemon {
  constructor(name, shinyrate) {
    this.name = name;
    this.shinyrate = shinyrate;
  }
}
const pokemon = {
    "bulbasaur": new Pokemon('Bulbasaur', base)
};

function shundoWild() {
  let mon = pokemon[document.getElementById("list").value];
  let nowb = mon.shinyrate * ivCombinations(ivFloor.wild);
  let wb = mon.shinyrate * ivCombinations(ivFloor.weatherBoost);
  document.getElementById("print").innerHTML = ("The chance to get a SHUNDO " + mon.name + " wild catch is ~1/" + wb + " when weather boosted, or ~1/" + nowb + " when not weather boosted.")
}
<select id="list" onchange="shundoWild();">
  <option value="bulbasaur">Bulbasaur</option>
  <option value="ekans">Ekans</option>
</select>

不是创建 bulbasaurekans 变量,而是将它们设置为对象的属性:

const characters = {
  bulbasaur: new Pokemon('Bulbasaur', base),
  ekans: new Pokemon('Ekans', base)
}

您可以通过名称访问它们:

  let name = document.getElementById("list").value;
  const mon = characters[name];