使用 location.hash 将页面状态保持在 javascript

use location.hash to keep page status in javascript

我正在练习使用 location.hash 来保持页面状态,我使用下面的代码所做的是

1.click任何按钮,按钮的内部HTML会被写入div#cont

2.refresh 页面,它保留 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。

最终目标是

  1. 点击其中一个A\B\C,数值将写入'contABC'

  2. 点击其中一个D\E\F,数值将写入'contDEF'

  3. 页面刷新时保持更改

因为这次要记录两个值,我不知道怎么用哈希来做,谁能帮忙?提前致谢!

这是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>

尝试构建存储散列值的方式,例如使用分隔符-

<body>
<button data-attr='ABC' id="a">A</button>
<button data-attr='ABC' id="b">B</button>
<button data-attr='ABC' id="c">C</button>
<button data-attr='DEF' id="d">D</button>
<button data-attr='DEF' id="e">E</button>
<button data-attr='DEF' id="f">F</button>
<div id="contABC"></div>
<div id="contDEF"></div>
<script>
// var hashValue;
function getHash() {
    var hashValue = location.hash && location.hash.slice(1);
    return hashValue && hashValue.split('-');
}
function draw() {
     var cont = getHash();
    if (cont && cont.length>0) {
        document.getElementById('contABC').innerHTML = cont[0];
        document.getElementById('contDEF').innerHTML = cont[1];
    }
}

btns = document.getElementsByTagName('button');
var seperator = '-';
for (i = 0; i < btns.length; i++) {
    btns[i].index = i;
    btns[i].onclick = function() {
        var cont = getHash() || [];
        if(btns[this.index].dataset.attr=='ABC'){
            location.hash = btns[this.index].innerHTML + seperator + cont[1];
        }else{
            location.hash =  cont[0] +  seperator + btns[this.index].innerHTML ;
        }
    }
}
window.onhashchange = function() {
    draw();
}
draw();
</script>
</body>