Javascript 将变量与 window.location.href 一起使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5573351/
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
use variable with window.location.href
提问by Matt
I was wondering how I would be able to execute a command such as this in javascript. I just want to store the url as a string in a variable and redirect them to it when the time comes -
我想知道如何在 javascript 中执行这样的命令。我只想将 url 作为字符串存储在变量中,并在时机成熟时将它们重定向到它 -
var linkz = "http://www.google.com/";
window.location.href= linkz;
Why doesn't this work?
为什么这不起作用?
Thanks,
谢谢,
采纳答案by typeof
If you're using links this way (as mentioned in a comment):
如果您以这种方式使用链接(如评论中所述):
<a href="javascript:checkCk(google.com)">Google</a>
Then the problem is that you're not passing a string to your checkCk()
function.
那么问题是您没有将字符串传递给您的checkCk()
函数。
Try this:
试试这个:
<a href="javascript:checkCk('http://google.com')">Google</a>
The code you used for window.location.href
should work.
您使用的代码window.location.href
应该可以工作。
At this point, I don't see why you'd use javascript if all you're doing is replacing the default behavior of the link.
在这一点上,如果您所做的只是替换链接的默认行为,我不明白您为什么要使用 javascript。
回答by Larry Cinnabar
I've just tried on my local machine, and it works:
我刚刚在我的本地机器上尝试过,它可以工作:
<script>
window.onload = function(){
var google = "http://google.com";
window.location.href = google;
}
</script>
Redirecting to google...
Copy this to new file, call it for example redirect.html
and open it in your browser.
将此复制到新文件,例如调用它redirect.html
并在浏览器中打开它。
Update:
更新:
<script>
var redirect = function(new_place) {
window.location.href = new_place;
}
</script>
<a href='javascript:redirect("http://google.com")'>Go to google</a>