我想做类似的事情:
1. 1296
2. 4624
Square root both numbers and add the result!
Answer: ________
[Check button]
如果答案正确,请打开somewhere.html
我制作了这个剧本:
<html>
<head>
<script language="javascript">
window.onload=calc;
function calc() {
var num1, num2, sqNum1, sqNum2, randomNum, sum, ans;
num1=Math.floor(Math.random()*90)+10;
num2=Math.floor(Math.random()*90)+10;
sqNum1=num1*num1;
sqNum2=num2*num2;
sum=num1+num2;
document.write("1. " + sqNum1 + "<br />");
document.write("2. " + sqNum2 + "<br />");
document.write("<br />");
}
function checkAns(form) {
if (form.ans.value==sum) {
location="somewhere.html";
} else {
alert ("Wrong answer!");
}
}
</script>
</head>
<body>
Square root both numbers and add the result! <br />
<form name='question'>
Answer: <input name='ans' type='password'> <br />
<input type='button' value='Check' onClick='checkAns(this.form)'>
</form>
</body>
</html>
无论我尝试什么,它都不会显示这一部分:
Square root both numbers and add the result!
Answer: ________
[Check button]
这个脚本有什么问题?
答案 0 :(得分:5)
当调用load
函数时,文档处于关闭状态。
您无法write
处于关闭状态的文档,因此调用write
会为您调用open
。
致电open
将清除现有文件。
新内容将写入新文档。
使用DOM manipulation(createElement
,appendChild
和朋友)修改现有文档。
答案 1 :(得分:-1)
你需要这样的东西:
<html>
<head>
<script language="javascript">
function calc() {
var num1, num2, sqNum1, sqNum2, randomNum, sum, ans;
num1=Math.floor(Math.random()*90)+10;
num2=Math.floor(Math.random()*90)+10;
sqNum1=num1*num1;
sqNum2=num2*num2;
sum=num1+num2;
document.getElementById("sum").value = sum;
var question = document.getElementById("question");
var numbers = document.getElementById("numbers");
var br = document.createElement('br');
var txt = document.createTextNode("1. " + sqNum1);
numbers.appendChild(txt);
numbers.appendChild(br);
var txt = document.createTextNode("2. " + sqNum2);
numbers.appendChild(txt);
txt.appendChild(question);
}
function checkAns(form) {
if (document.getElementById("ans").value == document.getElementById("sum").value) {
var newWin = open('somewhere.html','windowName','height=300,width=300');
} else {
alert ("Wrong answer!");
}
}
</script>
</head>
<body onload="calc();">
<form name='question'>
<div id="numbers">
</div>
<br/>
Square root both numbers and add the result! <br />
<div id="question">
Answer: <input id='ans' name='ans' type='password'> <br />
<input type='button' value='Check' onClick='checkAns(this.form)'>
</div>
<input id='sum' type='hidden' value=''/>
</form>
</body>
</html>
这不是最佳答案,它是您可以用来开发的一种方式