2014-04-13 48 views
0

我正在嘗試創建一個表示小學級乘法輔助的腳本。腳本選擇兩個隨機數並將它們相乘。然後你輸入你的答案,如果它是正確的,它說明你的工作很好,如果你不正確,它會陳述並回到你的提示(它不會讓你繼續,直到你做對了)。之後它會問你是否願意繼續是或否。如果是,則循環返回到初始功能,以返回另一組隨機數字以進行乘,洗,沖洗和重複操作。功能無法正常工作。語法錯誤?

由於某種原因,我的功能根本不起作用。您會在代碼中看到我嘗試放置window.alerts,所以我知道它正在運行該特定函數。唉,這兩種功能都沒有警報。我知道所有的代碼都不在我想要完成的內容中,我不一定要找人寫出整個腳本(需要自己學習),但功能不起作用。句法?任何幫助表示讚賞!

<!DOCTYPE html> 
<html> 
<head> 
    <script type="text/javascript"> 
    document.writeln ("<h2 style = 'color:blue' >"); 
    document.writeln ("Hello! Are you ready to learn some multiplication?"); 

    /* I don't believe either function is working properly and 
     I'm not entirely sure its syntax. I'm doin something wrong and 
     I'm gouging my eyes out!!! */ 
    do {  
     function start() { 
      var button = document.getElementById("go"); 
      button.addEventListener("click", fetchnumbers, false); 
      /* I add this to pop up during function 1 Just to check to see if its working*/ 
      window.alert ("function 1"); 
     } 

     function fetchnumbers() { 
      var math1 = Math.floor ((Math.random()*12)+1); 
      var math2 = Math.floor ((Math.random()*12)+1); 
      // I add this to pop up and display the numbers from the variables to ensure correct syntax for math function but heck no popup 
      window.alert (math1 + math2); 
     } 

     finish = window.prompt ("Are we done for today?\n\nYes = 1\nNo = 2"); 
    } while (finish == 2); 
    </script> 
</head> 
<body> 
    <br /> 
    <br /> 
    <form> 
     <input id="go" type="button" value="Yeah!"> 
     <!--the id is referenced in the start function.--> 
    </form> 
</body> 
</html> 
+0

Javascript中的「do」? – Niloct

+3

@Niloct:[It exists。](http://es5.github.io/#x12.6.1) – icktoofay

+0

你在哪裏調用'start'?另外,函數定義應該不是*。 –

回答

0

你的方法......有點奇怪......但主要問題是你的啓動函數從來沒有被調用。

您應該將函數移出do循環範圍,因爲我想您打算在您的頁面加載時調用start()一次。目前你的函數只能在do循環範圍內調用。

function start() { 
    var button = document.getElementById("go"); 
    button.addEventListener("click", fetchnumbers, false); 
    /* I add this to pop up during function 1 Just to check to see if its working*/ 
    window.alert ("function 1"); 
} 

function fetchnumbers() { 
    var math1 = Math.floor ((Math.random()*12)+1); 
    var math2 = Math.floor ((Math.random()*12)+1); 
    // I add this to pop up and display the numbers from the variables to ensure correct syntax for math function but heck no popup 
    window.alert (math1 + math2); 
} 
do { 
    finish = window.prompt ("Are we done for today?\n\nYes = 1\nNo = 2"); 
} while (finish == 2); 

此外,我建議針對document.write函數。他們更值得的是他們更麻煩。

這裏的示例http://jsfiddle.net/W2WY7/

+0

..對不起,我對JavaScript絕對陌生。我寫出來的方式一開始總是很奇怪,然後我把它清理乾淨。我總是把絨毛放在檢查代碼的地方。好吧,我添加了'窗口。addEventListener(「load」,start,false);'這樣調用函數。我要去看看'do'的聲明,看看它發生了什麼。謝謝你的幫助! – PimPedOutGeese

+0

@downvoter任何需要解決的問題? –

+0

@PimPedOutGeese不要擔心新事物。我們都是新的一次,JavaScript不完全是最簡單的語言。祝你的課程好運。 –