如何将路径嵌入到锚点 href 的当前路径?

How to embed path to the current path at anchor href?

例如,现在我在 http://example.com/practice

如果我在生成的页面中有 link:<a href="5">Click here</a>,我将被定向到 http://example.com/5

现在我知道这是相对路径的常用方法了。但我在这里真正需要的是 link 将带我到 http://example.com/practice/5,而无需在该页面上指定 practiceexample.com。如果可能的话不使用任何 Javascript 是首选,但如果不可能,那么我想我将不得不使用 Javascript。

我已经尝试过 <a href="./5">Click here</a><a href="./5/">Click here</a>,它们仍然像 "5" 一样工作。

请帮忙。谢谢。

您可以在 javascript 中使用 window.location.href 获取当前位置(可能有更好的方法,具体取决于您是否使用任何 js 框架)。例如对于此页面,window.location.href returns

然后你可以做这样的事情

var baseUrl = window.location.href;
var aTag = document.querySelector(<selector for your anchor tag>);
aTag.setAttribute("href", baseUrl + "/" + <url we want to go to>);

所以基本上我们获取我们的当前位置,更改我们想要导航到的标签的 href,然后在最后添加我们想要去的任何子路径。这是一种奇怪的方式,但正如我之前所说,如果您使用的是 React 或 angular 或其他一些框架或库,可能会有更简单的方法。