我正在尝试计算和打印乘法表的结果。
表单接受Number以及乘法的起始和结束范围。
结果应以" 12 x 1 = 12"的格式打印。等等
除了最后一行之外,所有内容都有效,以便在'内容'中打印计算结果。格。
结果只是闪烁了一秒钟。没有错误
HTML
<form name="multiply">
<p>Enter the number: <input type="number" id="myNum"></p>
<p>From: <input type="number" id="sValue"> To: <input type="number" id="eValue"></p>
<input type="submit" name="Calculate" onclick="timesTable()">
</form>
<div id="content"></div>
的Javascript
function timesTable() {
Num = document.getElementById("myNum").value;
startValue = document.getElementById("sValue").value;
endValue = document.getElementById("eValue").value;
var result = [];
for (var i = startValue; i <= endValue; i++) {
result[i] = Num * i;
document.getElementById("content").innerHTML = Num + " x " + i + " = " + result[i] + "<br>";
}
}
答案 0 :(得分:2)
你需要在for循环之后插入DOM。
function timesTable() {
total="";
Num = document.getElementById("myNum").value;
startValue = document.getElementById("sValue").value;
endValue = document.getElementById("eValue").value;
var result = [];
for (var i = startValue; i <= endValue; i++) {
result[i] = Num * i;
total=total+" "+ Num + " x " + i + " = " + result[i] + "<br>";
}
document.getElementById("content").innerHTML=total;
}
<form name="multiply" onsubmit="return false;">
<p>Enter the number: <input type="number" id="myNum"></p>
<p>From: <input type="number" id="sValue"> To: <input type="number" id="eValue"></p>
<input type="submit" name="Calculate" onclick="timesTable()">
</form>
<div id="content"></div>
答案 1 :(得分:1)
这是典型的关闭问题。它显示最后输入的值。
将您的代码更改为以下
function timesTable() {
Num = document.getElementById("myNum").value;
startValue = document.getElementById("sValue").value;
endValue = document.getElementById("eValue").value;
var result = [];
var content = document.getElementById("content");
var res=[];
for (var i = startValue; i <= endValue; i++) {
result[i] = Num * i;
res.push( (function(i) {
return Num + " x " + i + " = " + result[i] + "<br>"
})(i));
}
content.innerHTML = res;
}
<form name="multiply">
<p>Enter the number:
<input type="number" id="myNum">
</p>
<p>From:
<input type="number" id="sValue">To:
<input type="number" id="eValue">
</p>
<input type="submit" name="Calculate" onclick="timesTable()">
</form>
<div id="content"></div>
希望这有帮助