HTML元素即使定义了值也返回“ null”值

问题描述 投票:0回答:1

我正在制作一个基本的转换器应用程序,可以在以太坊的不同单位之间进行转换。该应用程序应该使用用户在etherAmount输入框中提供的任意数量的醚,并将其转换为etherUnits选择菜单中选择的任何单位。我的Javascript函数运行onchange,并采用etherAmount的值和etherUnits的值。

问题是,当我尝试运行它时,出现Cannot read property 'value' of null TypeError。

老实说,我真的很困惑错误的出处,因为两个函数输入都有定义的值。

产品编号:

const converter = require("ethereumjs-units")

//Takes value of ether input box and converts it
function convert() {

  //value of ether amount input box
  let etherInput = document.getElementById("etherAmount").value
  console.log(etherInput)
  //valuse of "convert to" box
  let etherUnit = document.getElementById("etherUnits").options
  let etherUnitVal = etherUnit.options[etherUnit.selectedIndex].value
  console.log(converter.lazyConvert(etherInput.toString() + " eth", etherUnitVal))
}

document.getElementById("ethUnits").onchange = convert()
<!DOCTYPE html>
<html>

<head>
  <title>Ethereum Unit Converter</title>
  <link rel="stylesheet" type="text/css" href="style.css">
  <script src="bundle.js" type="text/javascript"></script>
</head>

<body>
  <div id="container">
    <h1 id="title">Ethereum Unit Converter</h1>
    <div id="conversions">
      <form>
        <input type="text" id="etherAmount" value="1"> ether to
        <select id="etherUnits">
          <option id="wei" value="wei">Wei</option>
          <option id="mwei" value="mwei">Mwei/Lovelace/Picoether</option>
          <option id="gwei" value="gwei">Gwei/Shannon/Nanoether/Nano</option>
          <option id="szabo" value="szabo">Szabo/Microether/Micro</option>
          <option id="finney" value="finney">Finney/Milliether/Milli</option>
          <option id="ether" value="ether">Ether</option>
          <option id="kether" value="kether">Kether/Grand</option>
          <option id="mether" value="mether">Mether</option>
          <option id="gether" value="gether">Gether</option>
          <option id="tether" value="tether">Tether</option>
          <input type="submit" value="Convert">
        </select>
      </form>
    </div>
    <div id="resultsContainer">
      <p id="results"></p>
    </div>
  </div>

</body>

</html>
javascript html dom
1个回答
0
投票

无法读取null的属性'值']

包含value的对象是什么?

document.getElementById('etherAmount').value

实际上,您需要检查两件事:

  1. 打开开发人员控制台并输入document.getElementById('etherAmount'),如果它没有为您提供DOM中元素的快捷方式,那么您需要弄清楚您所编码的是removing元素还是什么。您需要编码需要添加元素到DOM。
  2. 您有一个JavaScript函数,其名称与元素的id属性/值相同。在开发人员控制台中使用typeof etherAmount(带括号的not
  3. typeof etherAmount())。

    Never

使用camelCase进行JavaScript中任何you定义。将etherAmount更改为ether_amount。专业人士不愿使用camelCase,因为标准机构使用它来在JavaScript中定义新对象/等。
© www.soinside.com 2019 - 2024. All rights reserved.