2016-02-19 86 views
0

我一直在试图有一个简单的乘法表程序重复,直到输入“-1”。我尝试了几个循环的不同变体,但是我获得的最成功只是重复提示问题。该代码的工作原理,直到我试图重复它。以下代码是作为一次性运行程序的工作版本。任何帮助赞赏。自动重复JavaScript功能在浏览器中,直到终止输入输入

function getVariables(){ 
    var table = parseInt(prompt("Enter table: ")); 
    var start = parseInt(prompt("Enter start: ")); 
    var end = parseInt(prompt("Enter end: ")); 

    if (isNaN(table) || isNaN(start) || isNaN(end)) { 
     alert("Please enter numerical integers only"); 

     getVariables(); 
    } 
    else { 
     timesTable(table, start, end); 
    } 
} 

function timesTable(table, start, end) { 
    for (;start <= end; start++) { 
     document.write(table + " * " + start + " = " + table * start  + "<br/>"); 
    } 
} 

var proceed = prompt("Do you want to display times tables? Press 'ENTER' to continue or enter '-1' to exit."); 

if (proceed != -1){ 
    getVariables(); 
} 
+0

https://developer.mozilla.org/en-US/docs/Web/API/document.write – Teemu

回答

0

对于是/否的问题,你应该使用confirm(),不prompt()

while (confirm("Do you want to display times tables?")) { 
    getVariables(); 
} 

但是,如果你想使用prompt,这是

while (prompt("Do you want to display times tables? Press 'ENTER' to continue or enter '-1' to exit.") == '-1') { 
    getVariables(); 
} 
+0

感谢您回复Barmar!我以前尝试过“while(提示)”版本,但是这反复执行提示问题。只有在输入“-1”后才显示乘法表。此外,当我尝试“while(confirm)”版本时,它不允许我需要的“-1”,并导致无限循环。我无法弄清楚为什么“while循环”在重复提示之前不会执行整个程序。 – user3393940

+0

这是因为浏览器在所有Javascript完成之前都不会重新显示DOM。只要你在Javascript循环中,你将不会在浏览器窗口中看到任何东西。 – Barmar

+0

而不是使用循环,使用网页上的按钮。当用户点击按钮时,运行'timesTable'函数。 – Barmar