我似乎无法弄清楚如何从外部文件中清除JS代码中的文本框速率,并希望得到一些帮助来弄清楚如何做到这一点。
有人可以帮助我编写代码以及它为什么以及如何工作,以便我可以学习和理解它,以便我可以有效和高效地编码它?
我在下面包含了所有原始代码。
.HTML
<!DOCTYPE html>
<html>
<head>
<title>Future Value Calculator</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="future_value.css">
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js">
</script>
<script src="future_value.js"></script>
</head>
<body>
<section>
<h1 id="heading">Future Value Calculator</h1>
<label for="investment">Investment Amount:</label>
<input type="text" id="investment">
<span id="investment_error"> </span><br>
<label for="rate">Annual Interest Rate:</label>
<input type="text" id="rate">
<span id="rate_error"> </span><br>
<label for="years">Number of Years:</label>
<input type="text" id="years">
<span id="years_error"> </span><br>
<label for="future_value">Future Value:</label>
<input type="text" id="future_value" disabled="disabled"><br>
<label> </label>
<input type="button" id="calculate" value="Calculate"><br>
</section>
</body>
</html>
JavaScript
var $ = function (id) {
return document.getElementById(id);
}
var calculateClick = function () {
var investment = parseFloat( $("investment").value );
var annualRate = parseFloat( $("rate").value );
var years = parseInt( $("years").value );
if (isNaN(investment) || investment < 100 || investment > 100000) {
alert("Investment must be an integer from 100 - 100,000.");
}
else if(isNaN(annualRate) || annualRate < .1 || annualRate > 12) {
alert("Annual rate must be a value from .1 - 12.");
}
else if(isNaN(years) || years < 1 || years > 50) {
alert("Years must be an integer from 1 - 50.");
}
// if all entries are valid, calulate future value
else {
futureValue = investment;
for ( i = 1; i <= years; i++ ) {
futureValue += futureValue * annualRate / 100;
}
$("future_value").value = futureValue.toFixed();
}
}
window.onload = function () {
$("calculate").onclick = calculateClick;
$("investment").focus();
}
rate = document.getElementById("rate");
rate.dblclick = "";
要在 JS 中的 "rate" 元素中添加一个 "ondblclick" 属性,它的世界看起来像这样:
$('rate').ondblclick = clearRate();
然后添加"clearRate()"函数:
function clearRate() {
$('rate').value = ''
}
这意味着当双击"rate"元素时,它将触发函数"clearRate()",它将"rate"的值设置为空字符串。