页面加载时正在读取URL片段

Reading URL fragments on page load

本文关键字:读取 URL 片段 加载      更新时间:2023-09-26

在我的web应用程序中,我有一个使用如下片段的URL:

http://example.com#login

我的问题是:我可以使用页面加载上的片段来打开我网站的特定部分吗?如果是,我如何使用Javascript或jQuery来读取和处理片段?

背景信息:我使用Remodal(https://github.com/VodkaBears/Remodal)将自定义模式窗口添加到我的网站。当模式窗口打开时,此插件会自动将片段附加到当前URL。我希望能够在页面加载时打开模式窗口。

您可以使用window.location.hash在加载时读取URL中的片段,并打开相关的模态。

var fragment = window.location.hash; // = '#login' in your example url
if (fragment) {
    $('a[href="' + fragment + '"]').remodal().open();
}

编辑:尽管片段没有添加到HTTP请求中是正确的,但浏览器仍然可以访问它。请参阅@RoryMcCrossan的回答。

https://blog.httpwatch.com/2011/03/01/6-things-you-should-know-about-fragment-urls/

第2段指出,URL片段不在HTTP请求中发送。

第2版

我的最终代码:

var fragment = window.location.hash;
if (fragment) {
    var modal = $('[data-remodal-id=' + fragment.slice(1) + ']');
    if (modal.length) modal.remodal().open();
}