由于某些原因,下面的代码在尝试重定向时不起作用。我尝试了其他几种方法,例如 window.location.href 等。唯一有效的是 window.open ("")
但是当我需要它时,它会在新窗口中打开一个页面。如果我执行 window.open("", "_self")
然后它就不会再工作了。如果我用 alert
替换 window.location
它工作正常,所以我认为整体代码是正常的,只是阻止它在同一页面上重定向。这个问题也出现在我的 Windows Chrome 和 Mac Firefox 上。
<html>
<head>
<script type="text/javascript">
function checkAnswers(){
getElementById("myQuiz");
if(myQuiz.elements[1].checked){
window.location = "www.google.com";
}else{
alert("Failed");
}
};
</script>
</head>
<body>
<img src="Castle.JPG" />
<form id="myQuiz" onsubmit="checkAnswers()" action="">
<p>Name the country this castle is located in?
<br/>
<input type="radio" name="radiobutton" value="A"/>
<label>England</label>
<input type="radio" name="radiobutton" value="B"/>
<label>Ireland</label>
<input type="radio" name="radiobutton" value="C"/>
<label>Spain</label>
<input type="radio" name="radiobutton" value="D"/>
<label>France</label>
<input type="submit" name="submit" value="Submit"/>
<input type="reset" name="reset" value="Reset"/>
</p>
</form>
</body>
</html>
最佳答案
将 js 更改为:
function checkAnswers()
{
var myQuiz=document.getElementById("myQuiz");
if (myQuiz.elements[1].checked) {
window.location.href = "http://www.google.com";
}
else {
alert("Failed");
}
return false;
};
和改变:
<form id="myQuiz" onsubmit="checkAnswers()" action="">
到
<form id="myQuiz" onsubmit="return checkAnswers();" action="">
关于javascript - window.location 在 javascript 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10646323/