例如,现在我在http://example.com/practice
如果我在生成的页面中有一个链接:<a href="5">Click here</a>
,我会定向到http://example.com/5
。
现在我知道这是相对路径的常用方法。但我在这里真正需要的是,链接会将我带到http://example.com/practice/5
,而无需在该页面上指定practice
或example.com
。如果可能的话,如果不使用任何Javascript,则首选,但如果不可能,那么我想我必须使用Javascript。
我已经尝试了<a href="./5">Click here</a>
和<a href="./5/">Click here</a>
,但它们的工作方式与"5"
完全相同。
请帮忙。感谢。
答案 0 :(得分:1)
您可以在javascript中使用window.location.href获取当前位置(根据您是否使用任何js框架,可能有更好的方法)。例如,对于此页面,window.location.href返回https://stackoverflow.com/questions/38284340/how-to-embed-path-to-the-current-path-at-anchor-href
然后你可以做这样的事情
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或其他框架或库,可能会有一种更简单的方法。