开发者

URL Hash oddities

I've noticed some strange behaviour in 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'

basically I want to trigger three conditions

  1. no hash
  2. just hash
  3. hash with text
开发者_C百科

however it seems like JS doesn't see the difference between example.com/ and example.com/# Also I can't figure out how to remove the hash completely.

Any help?


  1. Once the hash is set, you cannot remove it altogether (eg, remove the # sign) without causing a page reload; this is normal behavior.

  2. Setting an empty/null hash and setting the hash to the default hash (#) are treated the same; this is just internal behavior. Not sure if all browsers handle it consistently, but IIRC that is the case.

Ultimately if you want to remove the hash completely, you would have to do document.location.href = document.location.href, to reload the page (window.location.reload() would keep the hash).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜