【问题标题】:How to make JS store random elements in cache?如何让JS在缓存中存储随机元素?
【发布时间】:2019-08-19 12:58:34
【问题描述】:
我有这个代码:
<span id="result"></span>
<script>
document.getElementById("result").innerHTML =
Math.floor(Math.random() * 6) + 2;
</script>
它可以正常生成 2 到 6 之间的数字,但我想将该数字存储在用户的缓存中,因此如果他重新加载页面,将显示相同的数字。但我也希望,如果用户转到不同的 URL,但使用相同的代码,则会显示不同的数字。
总之:
如果用户首先加载我的网站并生成数字 3,则显示数字 3,如果用户返回同一网站,数字 3 将继续显示,但如果用户转到我网站内的另一个 URL相同的代码,那么它应该生成另一个数字。
提前致谢
【问题讨论】:
标签:
javascript
html
caching
【解决方案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
【解决方案2】:
试试这个:
// 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');
}