URL Hash奇怪

时间:2010-10-08 05:47:58

标签: javascript url fragment-identifier

我注意到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. 带文字的哈希
  4. 然而,似乎JS没有看到example.com/和example.com/#之间的区别 此外,我无法弄清楚如何完全删除哈希。

    任何帮助?

1 个答案:

答案 0 :(得分:2)

  1. 设置哈希值后,您无法完全删除它(例如,删除#符号)而不会导致页面重新加载;这是正常行为。

  2. 设置空/空哈希并将哈希设置为默认哈希(#)的方法相同;这只是内部行为。不确定所有浏览器是否一致地处理它,但IIRC就是这种情况。

  3. 最终如果你想完全删除哈希,你必须做document.location.href = document.location.href,重新加载页面(window.location.reload()将保留哈希)。