<分区>
<分区>
我想知道为什么我的控制台不会记录适当的日志。错误是说我的 .addEventListener()
是 null 但怎么会这样呢?
我试过:
删除 return false
但这没有帮助。
这是 gameTime.html
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="gameTime.js"></script>
<meta charset="utf-8">
<title>WOMP</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="gameTime.css">
</head>
<body>
<form class="col-md-4 col-md-offset-4" name="formHandler" id="handle">
<div id="allFields">
<div class="moveUsername">
<h1>(All numbers inputted will be assumed that it's in dollars)</h1>
<label for="usr">What's your annual salary?</label>
<input type="field" class="form-control" id="salary" placeholder="What's your annual salary?" required="required">
</div>
<div class="ageMovement">
<label for="usr">How much do you spend every month on bills?</label>
<input type="field" class="form-control" id="monthlyBills" name="ageChecker" placeholder="How much do you spend every month on bills?" required="required">
</div>
<div class="emailMovement">
<label for="usr">How much do you spend when going out?</label>
<input type="field" class="form-control" id="goingOut" name="emailChecker" placeholder="How much do you spend when going out?" required="required">
</div>
<button type="submit" id="btnSubmit" class="btn btn-default">Submit</button>
</form>
</body>
</html>
这是 gameTime.js
(function() {
function Finance(salary, fixedExpense, variableExpense) {
this.salary = salary;
this.fixedExpense = fixedExpense;
this.variableExpense = variableExpense;
this.isSalaryZeroOrLess = function() {
var s = parseInt(document.getElementById("salary").value);
console.log(this);
if (s <= 0) {
console.log("No money");
} else if (this.greaterThan()) {
console.log("Testing");
} else {
console.log("Money: ", s);
}
}
}
Finance.prototype.greaterThan = function() {
var s = parseInt(document.getElementById("salary").value);
var userSalary = s / 12;
console.log(userSalary);
if (userSalary < 30000) {
console.log("works!");
}
}
var fin = new Finance(1000, 1000, 1000);
document.querySelector("#btnSubmit").addEventListener("click", fin.isSalaryZeroOrLess);
return false;
})()
错误如下:
Uncaught TypeError: Cannot read property 'addEventListener' of null
at gameTime.js:30
at gameTime.js:32
最佳答案
您在 HTML 完全解析之前运行 JavaScript。所以当你的 addEventListener()
行被执行,#btnSubmit
甚至还没有到达元素。
移动这个:
<script type="text/javascript" src="gameTime.js"></script>
出自 head
部分,使其位于 </body>
之前标签:
<script type="text/javascript" src="gameTime.js"></script>
</body>
</html>
这样,当脚本执行时,构成页面正文的所有 HTML 都已经加载并在内存中。此外,通过在 HTML 末尾加载脚本,页面将比脚本位于页面顶部更快地呈现给用户,因为在加载和执行脚本时,浏览器无法执行任何其他操作。
仅供引用:return false;
在你的函数结束时没有为你做任何事情,因为:
此外,您的 Finance
函数不会暴露在你的 IIFE 之外,所以你永远无法在它之外使用它。
关于javascript - .addEventListener 不是 null 的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41335597/