Javascript 从 #anchor 重定向到单独的页面
我有一组带有 #anchors 的链接指向单个网页,我希望顺利地转移到每个链接都有一个单独网页的模型。我希望旧链接能够使用重定向继续工作。
旧链接样式:
/all_products#A
/all_products#B
/all_products#C
新链接样式:
/products/A
/products/B
/products/C
我知道服务器不会收到请求中的#anchor 名称,但 Javascript 可能会收到。
是否可以使用 Javascript 自动从 /all_products#A 重定向到 /products/A?
JQuery 就可以,无论如何,网站上都在使用它。
I have a set of links with #anchors pointing to a single webpage and I would like to smoothly move to a model with a separate webpage for each of those links. I want the old links to keep working using a redirect.
Old link style:
/all_products#A
/all_products#B
/all_products#C
New link style:
/products/A
/products/B
/products/C
I know that the server does not receive the #anchor name in the request but Javascript might.
Is it possible to automatically redirect from /all_products#A to /products/A using Javascript?
JQuery would be fine, it's being used on the site anyway.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我添加了这个新答案,以包含从网址中提取哈希和进行重定向。
I added this new answer to include some best practices for both extracting the hash from the url and doing a redirect.
将其尽可能靠近 HTML
的顶部,以便它可以在页面资源的其余部分下载之前执行:
这将检查当前页面 URL 并在匹配时进行重定向旧式路径。
此代码使用
window.location
对象,该对象包含当前 URL 的所有部分,这些部分已被拆分为多个组成部分。使这个脚本更加通用是留给实施者的练习。
Put this as close to the top of your HTML
<head>
as you can so that it can execute before the rest of the page resources download:This will check the current page URL and redirect if it matches the old-style path.
This code makes use of the
window.location
object which contains all the parts of the current URL already split up into component parts.Making this script more generic is left as an exercise for the implementer.
我希望这能有所帮助:)
I hope this can help :)
使用 jquery,要么只需将 href 替换为正确的:
或者捕获点击并重定向:
With jquery, either just replace the href with the correct one:
or capture clicks and redirect:
这可能有帮助:
this might help: