如何使用javascript进行相对路径重定向?

aru*_*air 16 javascript jquery

我正在基于php的网站上使用javascript/jquery,我必须在页面中的事件上重定向页面.

比方说,点击"点击我"按钮"page1.php",页面应重定向到" page2.php".必须使用javascript/jquery完成此重定向.两个页面都在同一个文件夹中,重定向代码应使用"RELATIVE LINKS".

现在,如果我给出绝对链接,我可以重定向page2.php,但有人可以让我知道如何使用相对链接做同样的事情吗?

就像是:

window.location.href = 'page2.php';
Run Code Online (Sandbox Code Playgroud)

谢谢.

aru*_*air 21

window.location.href = "page2.php";
Run Code Online (Sandbox Code Playgroud)

这很有效.事实上,相对和绝对的工作方式相同:

window.location.href = "http://www.google.com";
// or
window.location.href = "page2.html";
Run Code Online (Sandbox Code Playgroud)


Eni*_*ate 10

你可以做一个相对重定向:

document.location.href = '../'; //one level up
Run Code Online (Sandbox Code Playgroud)

要么

document.location.href = '/path'; //relative to domain
Run Code Online (Sandbox Code Playgroud)

或在jquery ...

 var url = "http://stackoverflow.com";    
$(location).attr('href',url);
Run Code Online (Sandbox Code Playgroud)


Jam*_*ill 5

设置相对路径使用window.location.pathname.

看看的MDN文档window.location: