Javascript:获取window.location除主机外的一切?

mat*_*att 9 javascript

我喜欢

http://www.mydomain.com/hello/you

top.location.host,我可以得到"http://www.mydomain.com"

window.location.href我能得到"http://www.mydomain.com/hello/you"

有没有机会得到"/hello/you"???

Anu*_*rag 21

location.pathname
Run Code Online (Sandbox Code Playgroud)

pathname返回的路径.如果您想要querystring和可选hash,您还需要组合searchhash属性.考虑这个网址:

http://www.example.com/path/to/glory?key=value&world=cup#part/of/page

location.pathname => "/path/to/glory"
location.search   => "?key=value&world=cup"
location.hash     => "#part/of/page"
Run Code Online (Sandbox Code Playgroud)

如果你想要整件事,

/path/to/glory?key=value&world=cup#part/of/page
Run Code Online (Sandbox Code Playgroud)

然后只是连接所有这些:

location.pathname + location.search + location.hash
Run Code Online (Sandbox Code Playgroud)

一直想在with某个地方使用.这看起来像是一个绝佳的机会:)

with(location) {
    pathname + search + hash;
}
Run Code Online (Sandbox Code Playgroud)