【问题标题】:How to embed path to the current path at anchor href?如何在锚点href嵌入到当前路径的路径?
【发布时间】:2016-11-12 01:35:42
【问题描述】:

例如,我现在在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" 完全一样。

请帮忙。谢谢。

【问题讨论】:

  • 只有“目录”在相对路径中被继承。因此,如果您想使用纯 html,则必须将当前路径设置为 'example.com/practice' - 否则只需使用 window.location 构建新路径。

标签: html href


【解决方案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 或其他框架或库,可能会有更简单的方法。

【讨论】:

  • 好吧,看来没有 Javascript 真的不可能。感谢您的解释和Javascript代码! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-24
  • 2020-10-27
相关资源
最近更新 更多