我目前正在学习 JavaScript。我创建了一个计算器来计算投资的 future 值(value)。当它显示 future 值
时,它给了我一个不正确的值。我已经检查了几次公式,但它仍然给我一个错误。此外,我还设置了当兴趣小于 0
或大于 20
时出现警报,但没有显示任何内容。我如何能够在必要时正确显示正确的 future 值和警报? Example
Javascript
var $ = function (id) {
return document.getElementById(id);
}
var calculate_click = function () {
var investment = parseFloat( $("investment").value );
var annualRate = parseFloat( $("rate").value ) /100;
var years = parseInt( $("years").value );
$("futureValue").value = "";
if (isNaN(investment) || investment <= 0) {
alert("Investment must be a valid number\nand greater than zero.");
} else if(isNaN(annualRate) || annualRate <= 0 || annualRate > 20) {
alert("Annual rate must be a valid number\nand less than or equal to 20.");
} else if(isNaN(years) || years <= 0 || years > 50) {
alert("Years must be a valid number\nand less than or equal to 50.");
} else {
//var monthlyRate = annualRate / 12;
//var months = years * 12;
var futureValue = 0;
for ( i = 1; i <= years; i++ ) {
futureValue = ( futureValue + investment ) *
( 1 + annualRate );
}
$("futureValue").value = futureValue.toFixed(2);
}
}
var clear_click = function () {
$("investment").value = "";
$("rate").value = "";
$("years").value = "";
$("futureValue").value = "";
}
window.onload = function () {
$("calculate").onclick = calculate_click;
$("investment").focus();
$("clear").onclick = clear_click;
}
最佳答案
使用.value
是不正确的,它是javascript,而这是jquery,请尝试在前面添加#
并使用.val()
相反。
与此类似:
jquery function val() is not equivalent to "$(this).value="?
编辑
他没有使用jquery,忽略这一点。
关于javascript - 使用javascript计算投资值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15821461/