出于某种原因,我的代码只是不想计算。我正在练习一本练习册,但在这方面并没有真正帮助我。总和我得到20000NaN,我知道这不是一个数字。如何才能正确计算?我尝试使用ParseFloat转换我的百分比。谢谢。
<form action="#" name="car">
<p> </p>
<p>Vehicle:
<select id="dropDown1">
<option selected value="370z, 20000, 10%, 8.5%">Accord</option>
<option value="M3, 18000, 8%, 8.5%">Altima</option>
<option value="Camaro, 19000, 9%, 8.5%">Camry</option>
</select>
<br />
<br />
</p>
<button type="button" onclick="car()" value="Submit">Book it now</button>
<br />
<br />
<textarea name="answer" cols="80" rows="3" disabled></textarea>
<br />
<br />
</form>
</div>
<script language="javaScript">
function car() {
var value = document.getElementById("dropDown1").value;
var split = value.split(",");
var v1 = split[0];
var v2 = split[1];
var v3 = split[2];
var v4 = split[3];
parseFloat(v3);
parseFloat(v4);
profit = v2*v3;
tax = v2*v4;
extra = profit+tax;
sum = v2 + extra;
document.car.answer.value = "You selected " + v1 + " " + "which has a base price of" + v2 + ", a profit of" + v3 + ", and sales tax of" + v4 + "." + " Total cost of this vehicle, including profit and sales tax is: $" + sum + "."
}
</script>
答案 0 :(得分:1)
解析float时需要指定值:
v3 = parseFloat(v3);
v4 = parseFloat(v4);
答案 1 :(得分:1)
你的大多数语法都不对。 这应该是这样的:
var test = function() {
var value = document.getElementById("dropDown1").value;
var split = value.split(",");
var v1 = split[0];
var v2 = split[1];
var v3 = split[2];
var v4 = split[3];
v3 = parseFloat(v3);
v4 = parseFloat(v4);
var profit = parseFloat(v2)*parseFloat(v3)/100;
var tax = parseFloat(v2)*parseFloat(v4)/100;
var extra = parseFloat(profit)+parseFloat(tax);
var sum = parseFloat(v2) + parseFloat(extra);
document.getElementById("answer").value = "You selected " + v1 + " " + "which has a base price of $" + v2 + ", a profit of " + v3 + "%, and sales tax of " + v4 + "%. Total cost of this vehicle, including profit and sales tax is: $" + sum + ".";
};
<form action="#" name="car">
<p> </p>
<p>Vehicle:
<select id="dropDown1">
<option selected value="370z, 20000, 10%, 8.5%">Accord</option>
<option value="M3, 18000, 8%, 8.5%">Altima</option>
<option value="Camaro, 19000, 9%, 8.5%">Camry</option>
</select>
<br />
<br />
</p>
<button type="button" onclick="test()" value="Submit">Book it now</button>
<br />
<br />
<textarea id="answer" cols="80" rows="3" disabled></textarea>
<br />
<br />
</form>
答案 2 :(得分:1)
使用:
v3=parseFloat(v3);
v4=parseFloat(v4);
而不是:
parseFloat(v3);
parseFloat(v4);