【发布时间】:2019-08-07 07:07:56
【问题描述】:
我正在做一个使用 location.hash 来保持页面状态的练习,我使用下面的代码所做的是
1.点击任意按钮,按钮的innerHTML会被写入div#cont
2.刷新页面,保持div#cont中的变化
<body>
<button id="a">A</button>
<button id="b">B</button>
<button id="c">C</button>
<div id="cont"></div>
<script>
// var hashValue;
function getHash() {
var hashValue = location.hash;
return hashValue;
}
function draw() {
var cont = getHash();
if (cont) {
document.getElementById('cont').innerHTML = cont.slice(1);
}
}
btns = document.getElementsByTagName('button');
for (i = 0; i < btns.length; i++) {
btns[i].index = i;
btns[i].onclick = function() {
location.hash = btns[this.index].innerHTML;
}
}
window.onhashchange = function() {
draw();
}
draw();
</script>
</body>
接下来我要实现的是添加三个其他按钮(D、E、F)和一个新的 div,当单击其中一个 D\E\F 时,innerHTMl 将写入新的 div。
最终目标是
点击A\B\C之一,数值会写入'contABC'
单击其中一个 D\E\F,值将写入 'contDEF'
在页面刷新时保留更改
因为这次它必须记录两个值,我不知道如何使用哈希来做到这一点,任何人都可以帮忙吗?提前致谢!
这是 HTML:
<button id="a">A</button>
<button id="b">B</button>
<button id="c">C</button>
<button id="d">D</button>
<button id="e">E</button>
<button id="f">F</button>
<div id="contABC"></div>
<div id="contDEF"></div>
【问题讨论】:
-
为什么要使用
window.hash?我更喜欢使用 HTML5 History API。 -
@MohammadRezaKhedri,感谢您的建议,我已经阅读了一些有关 html5 历史 API 的内容,我发现在这种情况下,history.pushstate 可以对 location.hash 做同样的事情。但是所有的例子都告诉我 pushstate 总是与 onpopstate 一起工作,而 popstate 是用来监视浏览器是后退还是前进。所以,在我的情况下,我是否应该仍然使用 # 作为 pushstate 的最后一个参数,如果 url 发生变化,我应该使用 onhashchange 到 mornitor,还是有其他方法可以实现我的情况?
标签: javascript html hash location