2014-02-20 50 views
1
<!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> 

所以,當我運行這個提示窗口不會自動彈出,它刷新時出現,我想在運行程序時出現。爲什麼不在頁面加載上運行此JavaScript,僅在刷新時運行?

回答

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

相關問題