我尝试了几种不同的方式,我觉得这个方法最接近工作,但它不起作用。我希望有人可以指出并解释我做错了什么。我认为parseFloat
可能是我的问题,但我不确定。
window.onload = function () {
var purchPrice = document.getElementById('purchPrice');
var warrMile = document.getElementById('warrMile');
var currentMile = document.getElementById('currentMile');
var purchMile = document.getElementById('purchMile');
var mileAdjPerct = 0;
var mileAdjEach = 0;
var mileAdjTotal = 0;
}
function warrUpdate() {
var warrPerct = (parseFloat(currentMile.value) - parseFloat(purchMile.value)) / parseFloat(warrMile.value);
var warrEach = parseFloat(purchPrice.value) * warrPerct;
var warrTotal = warrEach * 4;
parseFloat(document.getElementById('mileAdjPerct').value = warrPerct);
parseFloat(document.getElementById('mileAdjEach').value = warrEach);
parseFloat(document.getElementById('mileAdjTotal').value = warrTotal);
}
这是一个小提琴:http://jsfiddle.net/hmhxybLL/
答案 0 :(得分:1)
您的代码存在许多问题,主要问题是您要操作的变量是在onload回调函数中的本地范围。你必须使变量成为全局变量,但这是一个坏主意,因此在可以避免全局变量的许多事情中,一个是将所有代码封装在warranty
对象中:
<fieldset id="milewarr" onSubmit="milewarr()">
<p>Purchase Price Per Tire: <input type="number" name="purchPrice" id="purchPrice" onChange="warranty.update();" /></p>
<p>Mileage Warranty: <input type="number" name="warrMile" id="warrMile" onChange="warranty.update();" /></p>
<p>Current Vehicle Mileage: <input type="number" name="currentMile" id="currentMile" onChange="warranty.update();" /></p>
<p>Mileage at Purchase: <input type="number" name="purchMile" id="purchMile" onChange="warranty.update();" /></p>
<br />
<p>Adjustment Percentage: <input type="number" id="mileAdjPerct" readonly /></p>
<p>Adjustment Amount Each Tire: <input type="number" id="mileAdjEach" readonly /></p>
<p>Adjustment Discount Total: <input type="number" id="mileAdjTotal" readonly /></p>
</fieldset>
JS:
var warranty = (function() {
var purchPrice, warrMile, currentMile, purchMile, mileAdjPerct, mileAdjEach, mileAdjTotal;
return {
init: function() {
purchPrice = document.getElementById('purchPrice');
warrMile = document.getElementById('warrMile');
currentMile = document.getElementById('currentMile');
purchMile = document.getElementById('purchMile');
mileAdjPerct = document.getElementById('mileAdjPerct');
mileAdjEach = document.getElementById('mileAdjEach');
mileAdjTotal = document.getElementById('mileAdjTotal');
},
update: function() {
var warrPerct = (currentMile.value - purchMile.value) / warrMile.value; // caution: you should check for a divide by 0 first
var warrEach = purchPrice.value * warrPerct;
var warrTotal = warrEach * 4;
mileAdjPerct.value = warrPerct;
mileAdjEach.value = warrEach;
mileAdjTotal.value = warrTotal;
}
};
})();
window.onload = warranty.init;