五件事:
完全删除 的target属性form。默认是同一个窗口。虽然这并不重要,因为:
submit通过返回false您的取消事件onSubmit,因为您正在自己的代码中处理表单。一种简单的方法是让你的函数 return false,并在 中onSubmit,返回调用的结果。
此行不正确:
var response = document.getElementById('answer').value;
form元素没有value. 你想把它放在id元素input type="text"上。
hrefonlocation不是一个函数,它是一个属性。您只需分配给它(或直接分配给location)。
这有点微妙:因为您有一个名为 的全局函数answer,并且您有一个带有 的元素id "answer",所以存在冲突:两者都希望最终成为window对象的属性(不使用旧 DOM0onxyz属性或全局属性的众多原因之一功能,来吧)。因此,您需要更改其中之一的名称,例如,将功能更改为checkAnswer或类似。
所以:
<form onSubmit="return checkAnswer();">
<input id="answer" type="text" maxlength="55" class="box" autofocus />
<input type="submit" class="submit" value="SUBMIT" />
</form>
和:
function checkAnswer(){
var response = document.getElementById('answer').value;
if (response == "correctanswer")
location = 'right.html';
else
location = 'wrong.html';
return false;
}
完整示例:Live Copy | 直播源
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<form onSubmit="return checkAnswer();">
<input id="answer" type="text" maxlength="55" class="box" autofocus />
<input type="submit" class="submit" value="SUBMIT" />
</form>
<script>
function checkAnswer(){
var response = document.getElementById('answer').value;
if (response == "correctanswer")
location = 'http://jsbin.com/ukifoh/1'; // 'right.html';
else
location = 'http://jsbin.com/ukifoh/2'; // 'wrong.html';
return false;
}
</script>
</body>
</html>
我建议始终使用一致、有用的代码缩进,并且我非常喜欢始终使用带有控制结构的块,而不仅仅是语句。