为什么编译器说没有定义,即使它定义了?

时间:2017-03-04 13:13:18

标签: html css

我正在运行一些JavaScript,当我点击按钮时,控制台说它的调用功能没有定义。但我确实在它上面定义了它。我甚至将它记录到控制台,它说它是: function(){code}

问题出在哪里?



window.onload = function() {
  var userdata = document.getElementById("username").value;
  var pwdata = document.getElementById("passwordfield").value;
  var check = function() {
    alert("hey");
  };
  console.log(check);
}

<html>
<h1>Login</h1>
<input id="username" type="text" placeholder="Username" name="username">
<input type="password" id="passwordfield" placeholder="Password" name="password">
<button onclick="check()">Log in</button>

</html>
<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

window.onload之外定义函数,它将完美运行:

var check = function() {
  alert("hey");
};

window.onload = function() {
  var userdata = document.getElementById("username").value;
  var pwdata = document.getElementById("passwordfield").value;
  console.log(check);
}
<html>
<h1>Login</h1>
<input id="username" type="text" placeholder="Username" name="username">
<input type="password" id="passwordfield" placeholder="Password" name="password">
<button onclick="check()">Log in</button>

</html>

<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>