【问题标题】:How to let my HTML input be used by my JavaScript function?如何让我的 JavaScript 函数使用我的 HTML 输入?
【发布时间】:2021-05-20 10:46:39
【问题描述】:

所以我用我的 JavaScript 设置了许多对象,一个 HTML 下拉列表,你可以选择哪个口袋妖怪

如您所见,我尝试通过在下拉值为“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>

【问题讨论】:

  • 我给你做了一个sn-p。请将相关代码更新为minimal reproducible example - 我们需要 ivCombinations、ivFloor、wilde 等
  • 您还需要“请选择”,否则用户必须先选择 Ekans 才能选择球茎类恐龙

标签: javascript html function input output


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案2】:

    您可以将您的 Pokemon 枚举到一个 Object 结构中并按如下方式访问它:

    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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-26
      • 2013-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多