JavaScript 提交表格

JavaScript submit form

大家好,感谢您的宝贵时间。我在 JS 中提交表单时遇到问题。显然我的表格的值为“null”,但我不明白为什么。你能帮帮我吗,我是 JS 新手。

HTML:

<form id="form">
  <input type="text" id="username" placeholder="Username" required>
  <input type="email" id="email" placeholder="Email" required>
  <input type="submit" value="Register">
</form>

JS:

var form = document.getElementById('form')

form.addEventListener('submit',function(event){
  event.preventDefault()

  var username = document.getElementById("username").value
   console.log(username)
    
      var email = document.getElementById("email").value
      console.log(email)
    })

错误消息: 未捕获的类型错误:无法读取 null 的属性(读取 'addEventListener')

请确保您首先像这样加载 html:

<body>
  <form id="form">
    <input type="text" id="username" placeholder="Username" required>
    <input type="email" id="email" placeholder="Email" required>
    <input type="submit" value="Register">
  </form>
  <!--Javascript-->
  <script>
    var form = document.getElementById('form')

    form.addEventListener('submit',function(event){
      event.preventDefault()

      var username = document.getElementById("username").value
      console.log(username)
    
      var email = document.getElementById("email").value
      console.log(email)
    })
  </script>
</body>

除此之外还不错。