如何使JS在缓存中存储随机元素?

时间:2019-03-28 16:49:01

标签: javascript html caching

我有此代码:

<span id="result"></span>



        <script>
        document.getElementById("result").innerHTML =
        Math.floor(Math.random() * 6) + 2;
        </script>

它可以很好地生成2到6之间的数字,但是我想将该数字存储在用户的缓存中,因此,如果他重新加载页面,则将显示相同的数字。但是我也想,如果用户使用不同的URL,但使用相同的代码,则会显示不同的数字。

总之:

如果用户首先加载我的网站并生成了数字3,则显示数字3,如果用户返回相同的网站,则数字3将一直显示,但是如果用户使用以下命令转到我的网站内的另一个URL,相同的代码,那么它应该生成另一个数字。

预先感谢

2 个答案:

答案 0 :(得分:1)

尝试将随机数存储在用户的localStorage中,并将其映射到当前URL:

const stored = localStorage[location.href]
const number = stored || Math.floor(Math.random() * 6) + 2

document.getElementById("result").innerHTML = number

if ( !stored ) localStorage[location.href] = number

答案 1 :(得分:0)

尝试一下:

// Change yousite.com
let lastSite = document.referrer.search(/yoursite.com/gi);

if(lastSite =! -1) {
    document.getElementById("result").innerHTML = localStorage.getItem('random');
}
else {
    localStorage.setItem('random', Math.floor(Math.random() * 6) + 2);
    document.getElementById("result").innerHTML = localStorage.getItem('random');
}