Geo*_*ouh 7 javascript redirect function window.location
由于某种原因,下面的代码在尝试重定向时不起作用.我尝试过其他几种方法,比如window.location.href等等.唯一有效的是,window.open ("")但是当我需要它在同一个窗口时,这会在新窗口中打开一个页面.如果我window.open("", "_self")那么它再也不起作用了.如果我更换window.location用alert它工作得很好,所以我觉得整体的代码是正常的只是一些防止它在同一页上重定向.此问题也出现在我的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>
Run Code Online (Sandbox Code Playgroud)
art*_*twl 14
将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;
};
Run Code Online (Sandbox Code Playgroud)
并改变:
<form id="myQuiz" onsubmit="checkAnswers()" action="">
Run Code Online (Sandbox Code Playgroud)
至
<form id="myQuiz" onsubmit="return checkAnswers();" action="">
Run Code Online (Sandbox Code Playgroud)
当你改变位置时,你必须给它一个绝对的 URL:
location.href = '/some_page_on_my_site';
Run Code Online (Sandbox Code Playgroud)
或者:
location.href = 'http://www.google.com';
Run Code Online (Sandbox Code Playgroud)
或者:
location.href = '//www.google.com';
Run Code Online (Sandbox Code Playgroud)
最后一个将转到 http 或 https,具体取决于当前方案。谢谢@德里克