在我的网络应用程序中,我有一个使用像这样的片段的URL:
http://example.com#login
我的问题是:我可以使用页面加载上的片段来打开我网站的特定部分吗?如果是这样,我如何使用Javascript或jQuery来读取和处理片段?
背景信息:我使用Remodal(https://github.com/VodkaBears/Remodal)向我的网站添加自定义模态窗口。当打开模式窗口时,此插件会自动将片段附加到当前URL。我希望能够在页面加载时打开模态窗口。
答案 0 :(得分:3)
您可以使用window.location.hash
在加载的URL中读取片段并打开相关模式。
var fragment = window.location.hash; // = '#login' in your example url
if (fragment) {
$('a[href="' + fragment + '"]').remodal().open();
}
答案 1 :(得分:0)
编辑:虽然将片段添加到HTTP请求是正确的,但浏览器仍然可以访问它。请参阅@ RoryMcCrossan的答案。
https://blog.httpwatch.com/2011/03/01/6-things-you-should-know-about-fragment-urls/
第2段规定URL片段不会在HTTP请求中发送。
<强> EDIT2 强>:
我的最终代码:
var fragment = window.location.hash;
if (fragment) {
var modal = $('[data-remodal-id=' + fragment.slice(1) + ']');
if (modal.length) modal.remodal().open();
}