为什么这个javascript不会在页面加载时运行,只在刷新时?

时间:2014-02-20 22:26:18

标签: javascript

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type = "text/javascript">
    function problem(){
        var num1 = parseInt(Math.random()*11);
        var num2 = parseInt(Math.random()*11);  
        document.write("What is " + num1 + " + " + num2);
        var answer = num1 + num2;
        //document.write(answer);
        ans = prompt("Enter your answer??");
        if(ans == answer){
            alert("Good JOB!");
        }else{
            alert("Fail xD");
        }
    }
    problem();
</script>
</body>
</html>

所以,当我运行它时,提示窗口不会自动弹出,刷新时会出现,我想在运行程序时出现。

1 个答案:

答案 0 :(得分:2)

不要使用document.write,因为它会覆盖页面的内容。相反,创建一个元素来保存问题(如div)并将其引用为:

function problem() {
    var num1 = parseInt(Math.random() * 11);
    var num2 = parseInt(Math.random() * 11);
    document.getElementById('foo').innerHTML = "What is " + num1 + " + " + num2;
    var answer = num1 + num2;
    ans = prompt("Enter your answer??");
    if (ans == answer) {
        alert("Good JOB!");
    } else {
        alert("Fail xD");
    }
}
problem();

<强> jsFiddle example