javascript - window.location 在 javascript 中不起作用

标签 javascript function redirect window.location

由于某些原因,下面的代码在尝试重定向时不起作用。我尝试了其他几种方法,例如 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/

相关文章:

javascript - 在 AngularJS 中发出 GET 请求后,在 2 个 Controller 之间共享全局变量失败

javascript - 如何在php中获取服务器时间而不是本地时间

javascript - 扫雷 - Angular

php - 如何在 PHP 中将 "first day of the week"设置为星期四

c++ - 需要有关 Dissection C++ number 2 string function 的帮助

c++ - 没有STL和动态内存分配的成员函数类

.htaccess - URL重写如何添加额外条件

c - 如何将标准输出重定向到 ANSI C 中的字符串

jquery - 如果添加后使用JavaScript重定向,则无法将数据添加到sqlite数据库

javascript - 什么时候在 JavaScript 中使用 null 或 undefined?