如何在刷新时将阵列中的项目重复多次停止。
我尝试过拼接,但它不起作用,也许我做错了?
<script>
var r_text = new Array();
//Change the local links to server links
r_text[0] = '<a href="http://bitbulb.io/posts/9">Calculator</a>';
r_text[1] = '<a href="http://bitbulb.io/posts/8">Todo List</a>';
r_text[2] = '<a href="http://bitbulb.io/posts/10">Number Sorting Application</a>';
r_text[3] = '<a href="http://bitbulb.io/posts/11">Text Encryption / Decryption Application</a>';
r_text[4] = '<a href="http://bitbulb.io/posts/12">Alarm Clock</a>';
var i = Math.floor(r_text.length * Math.random());
document.write(r_text[i]);
</script>
答案 0 :(得分:2)
解决此问题的方法之一是使用localStorage并保存所有显示的链接。页面刷新后,您可以通过键和过滤器链接从localStorage获取值。因此,您只能获得未显示的链接
var key = 'ids';
var arr = [
'<a href="http://bitbulb.io/posts/9">Calculator</a>',
'<a href="http://bitbulb.io/posts/8">Todo List</a>',
'<a href="http://bitbulb.io/posts/10">Number Sorting Application</a>',
'<a href="http://bitbulb.io/posts/11">Text Encryption / Decryption Application</a>',
'<a href="http://bitbulb.io/posts/12">Alarm Clock</a>'
];
start(arr, key);
function start(arr, key){
var showedLinks = getFromStorage(key);
var len = arr.length;
if (showedLinks.length == len){
saveToStorage([], key);
showedLinks = [];
}
var unshowedLinks = arr.filter( link => showedLinks.indexOf(link) === -1);
var randomIndex = getRandom(unshowedLinks.length);
var randomLink = unshowedLinks[randomIndex];
var elem = document.createElement('div');
elem.innerHTML = randomLink;
document.body.appendChild(elem);
showedLinks.push(randomLink);
saveToStorage(showedLinks, key);
}
function getRandom(len){
return Math.floor(len * Math.random());
}
function saveToStorage(data, key){
window.localStorage.setItem(key, JSON.stringify(data));
}
function getFromStorage(key){
var data = window.localStorage.getItem(key);
return data? JSON.parse(data): [];
}