javascript 用 document.URL 替换当前 url
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15256877/
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
Replace current url with document.URL
提问by xhallix
I was trying to get the current URL and replace it with something else. But my code does not work if x = document.URL, but for x = "String" everything works perfectly
我试图获取当前 URL 并将其替换为其他内容。但是我的代码在 x = document.URL 时不起作用,但是对于 x = "String" 一切正常
function test(){
var x = document.URL
var url = window.location.toString();
window.location = url.replace( x , 'whatever');
}
test();
Thank you for helping me out
谢谢你帮我解决
回答by Chirag Bhatia - chirag64
The values of the variables url
and x
are the same, so you're simply replacing the whole URL with 'whatever'. Why not just use window.location = 'whatever'
instead?
变量url
和的值x
相同,因此您只需将整个 URL 替换为“随便”即可。为什么不直接使用window.location = 'whatever'
呢?
If you want the whole URL to be replaced, you need to give a complete URL in the string where you've put whatever
, otherwise it will act as a relative URL instead of an absolute one.
如果要替换整个 URL,则需要在放置的字符串中提供完整的 URL whatever
,否则它将充当相对 URL 而不是绝对 URL。
So try something like window.location = "http://www.google.com"
所以尝试类似的东西 window.location = "http://www.google.com"
回答by Vivek Ghaisas
You should just use window.location.href = 'whatever'
. Wouldn't that solve your problem?
你应该只使用window.location.href = 'whatever'
. 那不能解决你的问题吗?
window.location = 'whatever'
works too, but it's technically incomplete. Javascript will, however, implement it correctly.
window.location = 'whatever'
也可以,但技术上不完整。但是,Javascript 将正确实现它。