【问题标题】:base href to / - now href to IDs not workingbase href to / - 现在对 ID 的 href 不起作用
【发布时间】:2016-06-01 17:43:25
【问题描述】:

在我的html<head>中,我定义了以下<base>

<base href="/" target="_blank">

现在我无法链接到同一页面上带有 ID 的标签,例如:

<sup id="ref1" name="ref1"><a href="#fn1" target="_top">1</a></sup>

<p class="footnote" id="fn1" name="fn1">
    <a href="#ref1" title="back" target="_top">&#8617;</a>
</p>

指向 ID 的链接将我带回到根目录,而不是指定的 ID。我可以以某种方式强制&lt;a&gt; 元素在当前文档中查找ID,而不必删除&lt;base&gt; 中的href="/"

【问题讨论】:

标签: html href root base


【解决方案1】:

试试:

$(document).ready(function() {
    var pathname = window.location.href.split('#')[0];
    $('a[href^="#"]').each(function() {
        var $this = $(this),
            link = $this.attr('href');
        $this.attr('href', pathname + link);
    });
});

这将修复所有链接或(不带 jQuery)单个链接:

<a href="javascript:;" onclick="document.location.hash='anchor';">Anchor</a>

来源:Make anchor links refer to the current page when using <base>

【讨论】:

  • 谢谢,这行得通。我还找到了以下工作的解决方案:&lt;a href="path/filename.html#ref1" title="back" target="_top"&gt;&amp;#8617;&lt;/a&gt;
  • 是的,假设您在path/filename.html 上也可以。提供的答案更通用,因为它允许您使用不依赖于页面名称的相对锚。例如,如果您重命名filename.html -> foo.html,则必须更改所有链接。这也适用于不同的页面(每个页面的代码相同)。不过,您的解决方案不使用 JS,因此这也是可取的。
猜你喜欢
  • 1970-01-01
  • 2012-09-30
  • 1970-01-01
  • 2019-04-15
  • 1970-01-01
  • 2017-10-21
  • 2012-03-10
  • 2012-10-01
  • 1970-01-01
相关资源
最近更新 更多