我目前有一项任务需要一些变量,并将它们放在一个基于表单的计算器中,该计算器将信息传递给javascript,然后在计算后更新。我使用书中的示例将表单放在一起,但是当我单击buttom将信息发送到Javascript时,我只会看到一个页面显示“没有收到数据”。我看了几个小时,但我不知道到底发生了什么。HTML表单不提交,
HTML:
<!doctype html>
<html lang="en">
<head>
<title>Paycheck Calculator</title>
<meta charset="utf-8">
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<form action="" method="post" id="theForm">
<fieldset>
<p>Use this form to calculate your paycheck.</p>
<div><label for="hours">Hours Worked</label><input type="text" name="hours" id="hours" value="0.00"></div>
<div><label for="rate">Pay Rate</label><input type="text" name="rate" id="rate" value="0.00"></div>
<div><label for="withholding">Withholding</label><input type="text" name="withholding" id="withholding" value="0.20"></div>
<div><label for="total">Total</label><input type="text" name="total" id="total" value="0.00"></div>
<div><label for="withheld">Withheld</label><input type="text" name="withhheld" id="withheld" value="0"></div>
<div><label for="realTotal">Final Total</label><input type="text" name="realTotal" id="realTotal" value="0"></div>
<div><input type="submit" value="Calculate" id="submit"/></div>
</fieldset>
</form>
<script src="js/paycheck.js"></script>
</body>
</html>
的Javascript:
function calculate() {
'use strict';
var totalPay;
var withheld;
var realPay;
var hours = document.getElementById('hours').value;
var rate = document.getElementById('rate').value;
var withholding = document.getElementById('withholding').value;
totalPay = hours * rate;
withheld = totalPay * withholding;
realPay = totalPay - withheld;
document.getElementbyId('total').value = totalPay;
document.getElementById('withheld').value = withheld;
document.getElementById('realTotal').value = realPay;
return false;
}
function init() {
'use strict';
document.getElementById('theForm').onsubmit = calculate;
}
它几乎看起来与教科书的例子有什么不同,以及由于某种原因,他们的工作和我没有。这让我疯狂!请告诉我这是明显的和愚蠢的。
你肯定问题不是标题正好相反,那形式实际上提交? – adeneo 2014-09-10 23:12:07
很高兴提供JSFIDDLE! – 2014-09-10 23:22:16
看起来您可能已经忘记运行设置'onsubmit'绑定的'init'方法。你需要在主体中使用'window.onload = init'或'onload'属性。虽然有更好的方法来处理onload事件。阅读更多关于这个东西在这里http://stackoverflow.com/questions/191157/window-onload-vs-body-onload – 2014-09-10 23:26:14