我的alert("No money")
工作正常但我的alert("works!")
怎么办不起作用?这些错误对我来说没有意义,因为我觉得我写的东西在语法上是正确的。
感谢您花时间阅读:D
这是我的gameTime.html
<!DOCTYPE html>
<html lang="en">
<head>
<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>
</div>
<button type="submit" class="btn btn-default" onclick="fin.isSalaryZeroOrLess()">Submit</button>
</form>
<script type="text/javascript" src="gameTime.js"></script>
</body>
</html>
这是我的gameTime.js
function Finance(salary, fixedExpense, variableExpense) {
this.salary = salary;
this.fixedExpense = fixedExpense;
this.variableExpense = variableExpense;
this.isSalaryZeroOrLess = function() {
var s = parseInt(document.getElementById("salary").value);
if(s <= 0) {
alert("No money");
}
}
}
Finance.prototype.greaterThan = function() {
var s = parseInt(document.getElementById("salary").value);
var userSalary = s / 12;
if(userSalary < 30000) {
alert("works!");
}
}
var fin = new Finance(1000,1000,1000);
以下是错误:
Uncaught TypeError: Cannot set property 'greaterThan' of undefined
at gameTime.js:14
gameTime.html:28 Uncaught TypeError: Cannot read property 'isSalaryZeroOrLess' of undefined
at HTMLButtonElement.onclick (gameTime.html:28)
答案 0 :(得分:1)
如评论所示,您收到错误:
gameTime.html:28未捕获的TypeError:无法读取未定义的属性'isSalaryZeroOrLess' 在HTMLButtonElement.onclick(gameTime.html:28)
因为,您正在尝试在HTML中绑定事件
<button type="submit" class="btn btn-default" onclick="fin.isSalaryZeroOrLess()">Submit</button>
</form>
<script type="text/javascript" src="gameTime.js"></script>
但如您所见,您的gameTime.js
尚未加载。所以fin
尚未确定。
快速解决方案:
将脚本标记移到头部。
强大的解决方案
将事件侦听器移动到JS文件并使用.addEventListener
并将代码包装在函数( IIFE )中,以避免污染全局范围。
我已更新您的代码及其正常工作: JSFiddle
答案 1 :(得分:0)
你不能调用更强大的功能。您只需定义它并附加到Finance原型,我就不会看到您曾经使用过它。