我目前有一項任務需要一些變量,並將它們放在一個基於表單的計算器中,該計算器將信息傳遞給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