2

我注意到 JS 中有一些奇怪的行为

window.location.hash = '';
var hash = window.location.hash;
alert(hash + ' = ' + hash.length);
//outputs: ' = 0'
window.location.hash = '#';
hash = window.location.hash;
alert(hash + ' = ' + hash.length);
//outputs: ' = 0'
window.location.hash = '_';
hash = window.location.hash;
alert(hash + ' = ' + hash.length);
//outputs: '_ = 2'

基本上我想触发三个条件

  1. 没有哈希
  2. 只是哈希
  3. 带文本的哈希

但是似乎 JS 没有看到 example.com/ 和 example.com/# 之间的区别我也不知道如何完全删除哈希。

有什么帮助吗?

4

1 回答 1

2
  1. 一旦设置了哈希值,您就不能完全删除它(例如,删除#符号)而不导致页面重新加载;这是正常行为。

  2. 设置空/null 散列和将散列设置为默认散列 ( #) 的处理方式相同;这只是内部行为。不确定所有浏览器是否一致地处理它,但 IIRC 就是这样。

最终,如果您想完全删除散列,则document.location.href = document.location.href必须重新加载页面(window.location.reload()将保留散列)。

于 2010-10-08T05:51:43.930 回答