在 JavaScript 中设置 window.location 时页面不会重定向

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17671266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:08:38  来源:igfitidea点击:

Page does not redirect when setting window.location in JavaScript

javascripthtmlredirectwindow.location

提问by User007

I am trying to redirect the page dynamically depending upon the value of the dropdown box. I get the value of drop down box in JavaScript. Depending on the dropdown value I want to redirect the page.

我正在尝试根据下拉框的值动态重定向页面。我在 JavaScript 中获取下拉框的值。根据下拉值,我想重定向页面。

This is sample code:

这是示例代码:

<script type="text/javascript">
        function RedirectMe(){
            var chosanDept = document.getElementById("Dept");
            var str = chosanDept.options[chosanDept.selectedIndex].text;
            if(str=='HR')
                { 
                    alert('Yes in IF' + str);
                    window.location = "http://www.google.com";
                }
        }
    </script>

here chosanDeptis the variable to get the value of dropdown box. But I am not able to redirect page using various function like window.location, location.replace, location.href. And one more my if condition works, I get the alert 'Yes in IF HR'

chosanDept是获取下拉框值的变量。但我无法使用各种函数(如 window.location、location.replace、location.href)重定向页面。还有一个我的 if 条件有效,我收到警报“是在 IF HR”

What goes wrong here?

这里出了什么问题?

回答by Fiona - myaccessible.website

Try adding return false;to the end of your RedirectMe()function

尝试添加return false;RedirectMe()函数的末尾

And then wherever you are calling the function, make sure you put returnthere, like onclick="return RedirectMe();"

然后无论您在何处调用该函数,请确保将其放在return那里,例如onclick="return RedirectMe();"