hash是什么
hash 属性是一个可读可写的字符串,该字符串是 URL 的锚部分,一般有当前页面中href中#地址触发
- hash的改变不会导致页面重新加载;
- 使用浏览器访问网页时,如果网页URL中带有hash,页面就会定位到id(或name)与hash值一样的元素的位置;
- 通过window.location.hash属性获取和设置hash值。
hashchange事件
(window.onhashchange)
当hash值发生变化时会触发该事件,a标签的href为一个锚链接
<a href="#id"></a>
当被点击时:浏览器地址栏会发生如下变化
file:///C:/Users/Administrator/Desktop/3.16/05/%E4%BB%A3%E7%A0%81/pra.html
=>
file:///C:/Users/Administrator/Desktop/3.16/05/%E4%BB%A3%E7%A0%81/pra.html#id
此时就会触发hashchange事件
hash最简单应用
代码实例
页面中有5个不同的a标签,当点击不同的a时给filterText赋予不同的值,可利用window.onhashchange事件来实现,这样避免了给每个a标签分别注册事件
<a href="#/"></a>
<a href="#/active"></a>
<a href="#/completed"></a>
//此函数监听hash值的变化,来给判断哪个按钮被点击,从而给filterText赋值
let filterText = 'all'
window.onhashchange = function () {
switch(window.location.hash) {
case '#/':
filterText = 'all'
break
case '#/active':
filterText = 'active'
break
case '#/completed':
filterText = 'completed'
}
}