簡體   English   中英

為什么當我 console.log() 時它說未定義?

[英]Why does it say undefined when i console.log()?

我剛開始學習 javascript。 我有未定義的錯誤。 如何從 HTML 表單中獲取用戶輸入並將其保存在 javascript 中作為可在整個 javascript 中使用的全局變量?

html代碼

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>sort</title>
    <link rel="stylesheet" href="src1/style.css">
  </head>
  <body>
    <form class="" action="index.html" method="post">
      <input id="input" type="text" value="" ><br>
    </form>
    <button type="button" name ="button" onclick="saveinput()" >submit</button>    
    <script src = "src1/main.js"></script>
  </body>
</html>

javascript 代碼:

var i;
function saveinput(){
  i = document.getElementById("input").value;

}
console.log(i)

將您的console.log()放在您的 function 中,否則它將首先運行並打印undefined

在調用saveinput function 之前, i的值是未定義的。

 var i; function saveinput(){ i = document.getElementById("input").value; console.log(i); }
 <form class="" action="index.html" method="post"> <input id="input" type="text" value="" ><br> </form> <button type="button" name ="button" onclick="saveinput()" >submit</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM