我知道如何转到link / url / address,比如;
window.location = "www.example.com/index.html";
或
document.location.href="www.example.com/index.html";
但是假设我想要从index1.html
导航到index2.html
,如何在不提供www.example.com/
前缀的情况下实现这一点呢?请不要建议我在全局变量/常量中设置www.example.com/
。地址可能会更改为www.example2.com/subfolder1/subfolder2/
to www.examplea.com/
....。上述方法仅在根页面的情况下有效。我的意思是,提供document.location.href="index.html";
会将浏览器导航到rootdomain/index.html
,即使我停留在rootdomain/section1/section2/somepage.html
中。但是我想导航到rootdomain/section1/section2/index.html
如何通过只提供页面名称来实现这一点?
发布于 2013-03-30 23:31:09
如果字符串的开头有一个/
,它将转到本地页面:
window.location = "/index.html"
发布于 2013-03-30 23:30:50
window.location.pathname = 'index2.html';
您也可以只在document.location.href
上使用相对urls。
可能更好的是window.location.assign('index2.html');
。当您在www.example.com/foo/.../index1.html并且不想指定访问www.example.com/foo/.../index2.html的完整路径时,这特别有用。
有关更多选项,请参阅https://developer.mozilla.org/en-US/docs/DOM/window.location。
发布于 2013-03-30 23:31:07
就像您在其他地方所做的一样,但使用相对路径:
document.location.href = '/index2.html'; //relative path
https://stackoverflow.com/questions/15720175
复制相似问题