【问题标题】:It is possible to redirect HTML anchors using JavaScript/jQuery?可以使用 JavaScript/jQuery 重定向 HTML 锚点吗?
【发布时间】:2020-01-26 13:00:25
【问题描述】:

我目前正在开发具有多种旧版短链接格式的网站。其中一个特别成问题,因为它链接到不再存在的 HTML 锚点(特别是使用 id 而没有前导零的段落号)。 格式的段落编号带有 前导零;虽然这使事情变得可预测,但它也打破了旧的短链接。


示例

旧短链接:https://example.org/?AC_I_1

预期目标:https://example.com/augsburg-confession/article-i/#ac-i-0001


从旧格式重定向到新格式相对来说是微不足道的,但到目前为止,正则表达式只需要一个。在这种情况下,问题在于锚值没有发送到服务器,因此无法重写/重定向。相反,显然需要客户端解决方案(例如 JavaScript)。

目标

因此,目标是将所有少于四位数的段落编号(即HTML id's)重定向到它们的四位数等效项(例如,/#1> > #0001)。


在寻找实现这一点的方法时,我遇到了this answer,这似乎是一个好的开始,但我不确定如何更改它以说明段落编号。

【问题讨论】:

  • 在这种情况下使用 attr 可能很有用,可以根据您指定的条件动态更新 jQuery 中的锚元素。

标签: javascript jquery html wordpress


【解决方案1】:

您可以将数字更改为具有前导零,如下所示:

("0000" + number).slice(-4)

然后就可以得到旧href里面的数字,加上前导零:

("0000" + oldLink.href.replace("https://example.org/?AC_I_", "")).slice(-4)

为了更改为新格式,新的href应该是这样的:

"https://example.com/augsburg-confession/article-i/#ac-i-" + ("0000" + oldLink.href.replace("https://example.org/?AC_I_", "")).slice(-4) 

因此,要更改所有旧锚点,请在加载查询选择器后获取它们:

let oldLinks = document.querySelectorAll("a[href^='https://example.org/?AC_I_']");

并使用 forEach 更改 href:

oldLinks.forEach(function (oldLink) {
  oldLink.href = "https://example.com/augsburg-confession/article-i/#ac-i-" + ("0000" + oldLink.href.replace("https://example.org/?AC_I_", "")).slice(-4) 
})

以一些链接为例:

let oldLinks = document.querySelectorAll("a[href^='https://example.org/?AC_I_']");
console.log("anchors before change:", oldLinks)
oldLinks.forEach(function (oldLink) {
  oldLink.href = "https://example.com/augsburg-confession/article-i/#ac-i-" + ("0000" + oldLink.href.replace("https://example.org/?AC_I_", "")).slice(-4) 
})
console.log("anchors after change:", oldLinks)
<p><a href="https://example.org/?AC_I_1" rel="nofollow noreferrer">https://example.org/?AC_I_1</a><p/>
<p><a href="https://example.org/?AC_I_2" rel="nofollow noreferrer">https://example.org/?AC_I_2</a><p/>
<p><a href="https://example.org/?AC_I_3" rel="nofollow noreferrer">https://example.org/?AC_I_3</a><p/>
<p><a href="https://example.org/?AC_I_4" rel="nofollow noreferrer">https://example.org/?AC_I_4</a><p/>
<p><a href="https://example.org/?AC_I_5" rel="nofollow noreferrer">https://example.org/?AC_I_5</a><p/>
<p><a href="https://example.org/?AC_I_10" rel="nofollow noreferrer">https://example.org/?AC_I_10</a><p/>
<p><a href="https://example.org/?AC_I_50" rel="nofollow noreferrer">https://example.org/?AC_I_50</a><p/>
<p><a href="https://example.org/?AC_I_213" rel="nofollow noreferrer">https://example.org/?AC_I_213</a><p/>
<p><a href="https://example.org/?AC_I_3204" rel="nofollow noreferrer">https://example.org/?AC_I_3204</a><p/>

我希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2012-06-29
    • 1970-01-01
    • 2010-11-20
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 2011-12-01
    • 1970-01-01
    • 2015-09-26
    相关资源
    最近更新 更多