我写了一个小练习程序,显示提示号码的时间表。
我希望在询问用户输入哪个号码后显示该表。如果用户输入的数字不同于-1,我想要另一个号码。
我正在查找的序列是提示用户,显示表,提示用户显示表...不幸的是,我的程序工作的顺序是提示用户,提示用户,提示用户...并且只是在显示每个输入的表格之后。
显然,代码不是以这种方式编写的。
// get number to show time table for
var aNumber = prompt("Enter the number for time table or -1 to stop the program", "");
while(aNumber != -1) {
timeTableFrom(aNumber); // show time table for the first number
aNumber = prompt("Enter the number for time table or -1 to stop the program", ""); // ask for another number. HERE IS THE PROBLEM - THIS LINE RUNS BEFORE THE PREVIOUS ONE!
}
document.write("stopped");
function timeTableFrom(number)
{
for (var i = 0; i <= 10; i++)
{
document.write(number + " * " + i + " = " + number*i + "<br />");
}
}
&#13;
答案 0 :(得分:0)
// get number to show time table for
var aNumber = null;
var div = document.getElementById("textDiv");
setTimeout(enterNumber, 0);
function enterNumber()
{
aNumber = prompt("Enter the number for time table or -1 to stop the program", "");
if (aNumber != -1) {
timeTableFrom(aNumber); // show time table for the first number
setTimeout(enterNumber, 0);
}
else
div.innerHTML += "stopped"
}
function timeTableFrom(number)
{
for (var i = 0; i <= 10; i++)
{
div.innerHTML += number + " * " + i + " = " + number*i + "<br />";
}
}
&#13;
<div id="textDiv">
</div>
&#13;
@Teemu是对的。我承认,它有点草率,但这应该有效。尽量避免使用document.write,因为它可能会产生不可预测的结果。而是尝试其他methods of output