功能不起作用。语法错误?

时间:2014-04-13 02:45:48

标签: javascript function

我正在尝试创建一个代表基本等级乘法辅助工具的脚本。该脚本选择两个随机数并将它们相乘。然后你输入你的答案,如果它是正确的,它表示良好的工作,如果你不正确,它会说明并返回你的提示(它会让你继续,直到你做对了)。之后它会询问您是否继续是或否。如果是,请循环回到初始函数以返回另一组随机数以进行乘法,清洗,冲洗,重复。

由于某些原因,我的功能根本不起作用。您将在代码中看到我尝试放置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>

1 个答案:

答案 0 :(得分: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/