在 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
Page does not redirect when setting window.location in JavaScript
提问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
chosanDept
is 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 return
there, like onclick="return RedirectMe();"
然后无论您在何处调用该函数,请确保将其放在return
那里,例如onclick="return RedirectMe();"