location.hash 是用于获取或设置 URL 中的片段标识符(即“#”后面的部分),通常用于在单页面应用程序(SPA)中进行路由管理或页面内导航。
一些常见的使用技巧包括:
- 获取当前 URL 中的片段标识符:
var hash = location.hash;
console.log(hash); // 输出当前 URL 中的片段标识符
- 监听 URL 中片段标识符的变化:
window.addEventListener('hashchange', function() {
console.log('Hash changed:', location.hash);
});
- 设置 URL 中的片段标识符:
location.hash = '#section1'; // 将片段标识符设置为“#section1”
- 解析片段标识符中的参数:
var params = location.hash.substring(1).split('&').reduce(function(result, item) {
var parts = item.split('=');
result[parts[0]] = parts[1];
return result;
}, {});
console.log(params); // 输出解析后的参数对象
总的来说,location.hash 是一个方便的工具,可以帮助在单页面应用程序中管理页面状态和导航。