2010-10-08 87 views
2

我注意到在JSURL哈希古怪

一些奇怪的行为
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. 哈希文本

然而它看起来像J S没有看到example.com/和example.com/# 之间的区别此外,我不知道如何完全删除哈希。

任何帮助?

回答

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

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

最后,如果你想彻底删除哈希值,你就必须做document.location.href = document.location.href,重新加载页面(window.location.reload()将保持哈希)。

+0

所以不存在hash.length = 1的情况 – Moak 2010-10-08 05:53:15

+0

否 - 它将包含散列字符('#'),如果它是空的或者只有散列字符(与浏览器相同),则它报告0,而不管。 – mway 2010-10-08 05:54:44

+1

@Moak,这是正确的。你也无法判断'window.location.hash =='#''。它对''和'#'都返回false。 – helloandre 2010-10-08 05:58:20