[英]Why doesn't this javascript run on page load, only on refresh?
<!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>
So, when I run this the prompt window doesn't pop up automatically, it comes up when it refresh, I want to appear right when i run the program. 因此,当我运行此程序时,提示窗口不会自动弹出,而是在刷新时弹出,我希望在运行程序时显示正确。
Don't use document.write as it will overwrite the page's content. 不要使用document.write,因为它将覆盖页面的内容。 Instead, create an element to hold the question (like a div) and refer to it like:
相反,创建一个元素来保存问题(例如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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.