button.value未定义?

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

在尝试制作一个计算器的时候,我发现了一个无法解决的问题。在我的脚本中,我告诉浏览器,当一个按钮被点击时,它会将该按钮的值添加到计算器的显示中。例如,如果计算器当前显示的是 "455",而你点击了加号按钮,显示的文字就会变成 "455+",因为加号按钮的值是 "+")。

我在这里遇到的问题是,当我点击一个按钮时,"未定义 "代替该按钮的值添加。button.value 返回undefined而不是按钮的值?这里的问题是什么?

window.onload = () => {
  const calculator = document.querySelector('form[name = "calculator"]')
  const btns = document.querySelectorAll(`form[name = "calculator"] table tr td`)
  btns.forEach((button) => {
    button.addEventListener('click', () => {
      calculator.display.value += button.value
    })
  })
}
<!DOCTYPE html>
  <html>
    <head></head>
    </body>
      <!-- Page Contents !-->
      <form name = "calculator">
        <table>
          <tr>
            <input type = "text" name = "display" id = "display" disabled>
          </tr>
          <tr>
            <td><input type = "button" name = "one" value = "1"></td>
            <td><input type = "button" name = "two" value = "2"></td>
            <td><input type = "button" name = "three" value = "3"></td>
            <td><input type = "button" name = "plus" value = "+"></td>
          </tr>
        </table>
      </form>
      <script src = "script.js"></script>
    </body>
  </html>

如果我做错了什么,或者打破了任何 "规则",很抱歉,我是一个新的javascript程序员。谢谢!我是一个新的javascript程序员。

javascript html dom
1个回答
2
投票

你选择的是 <td>,不是 <input>. 改变选择器以选择按钮。

const btns = document.querySelectorAll(`form[name="calculator"] table tr td input[type="button"]`)
© www.soinside.com 2019 - 2024. All rights reserved.