我试图找到我的代码无法正常工作的原因,并且chrome回复了这个错误: 未捕获的ReferenceError:未定义calcMPG ... 有人能发现我的错误吗?(绝望)
<script type="text/javascript">
function calcMPG() {
document.calc.startingMileage.value = startMileage;
document.calc.endingMileage.value = endMileage;
document.calc.gallonsUsed.value = gallUsed;
var MPG = (endMileage - startMileage) / gallUsed;
if (isNAN(startMileage) || isNAN(endMileage) || isNAN(gallUsed)) alert('please type in numbers only!');
else document.calc.milesPerGalon.value = MPG;
}
</script>
<form name="calc">Starting mileage:
<input type="text" value="0" name="startingMileage" onchange="calcMPG()">
<br>Ending mileage:
<input type="text" value="0" name="endingMileage" onchange="calcMPG()">
<br>Gallons used:
<input type="text" value="0" name="gallonsUsed" onchange="calcMPG()">
<br>Miles per galon:
<input type="text" value="0" name="milesPerGalon">
</form>
答案 0 :(得分:6)
您的声明有误,请更正。
var startMileage = document.calc.startingMileage.value ;
var endMileage = document.calc.endingMileage.value;
var gallUsed = document.calc.gallonsUsed.value;
答案 1 :(得分:1)
startMileage
和你的其他右侧引用没有任何意义,它们是未定义的变量。
为您的输入提供ID并从中获取值,如下所示:
var startingMileage = document.getElementById('startingMileage').value;
答案 2 :(得分:1)
我不知道你为什么这样做,但试试这个:
<script type="text/javascript">
function calcMPG(){
var startMileage = document.calc.startingMileage.value,
endMileage = document.calc.endingMileage.value,
gallUsed = document.calc.gallonsUsed.value,
MPG = (endMileage - startMileage) / gallUsed;
if(isNaN(startMileage) || isNaN(endMileage) || isNaN(gallUsed)){
alert('please type in numbers only!');
} else {
document.calc.milesPerGalon.value = MPG;
}
}
</script>
<form name="calc">
Starting mileage:<input type="text" value="0" name="startingMileage" onchange="calcMPG()"><br>
Ending mileage:<input type="text" value="0" name="endingMileage" onchange="calcMPG()"><br>
Gallons used:<input type="text" value="0" name="gallonsUsed" onchange="calcMPG()"><br>
Miles per galon:<input type="text" value="0" name="milesPerGalon">
</form>
答案 3 :(得分:0)
点击此处Fiddle
function calcMPG(){
var startMileage = document.calc.startingMileage.value;
var endMileage = document.calc.endingMileage.value;
var gallUsed = document.calc.gallonsUsed.value;
var MPG = (endMileage - startMileage) / gallUsed;
if(isNaN(startMileage) || isNaN(endMileage) || isNaN(gallUsed))
alert('please type in numbers only!');
else
document.calc.milesPerGalon.value = MPG;
}