从预选链接中选择链接,然后一次转到所选链接

时间:2018-11-04 15:49:32

标签: javascript html

我想做类似的事情;仅访问一次所有链接,当访问完所有链接后,删除访问链接的数据并从头开始计算访问链接。

此代码很好用,但有时相同的链接会连续出现。

var urls=["http://randomemes.com/links/apotatoflewaround.html",
"youtube.com",
"yandex.com",
"google.com",

];
function goSomewhere() {
var e=Math.floor(Math.random()*urls.length);
window.location=urls[e],
urls.splice(e, 1)
}

<!-- begin snippet: js hide: false console: true babel: false -->
<input class="start" type="button" onClick="goSomewhere(); return ;" alt="Submit" width="800" height="100"value="»» Bring Memes ««">

1 个答案:

答案 0 :(得分:0)

问题是,您将在哪里保存访问了哪些链接?您不能只是从数组中删除项目,因为离开页面后不会保存这些值,因此当您返回页面时,将拥有完整的urls数组。您可以使用localStorage来存储数据。您可以为每个链接及其内部都有一个对象,例如urlvisited,以检查是否已访问该页面。但是localStorage不能存储javascript对象,只能存储变量和JSON字符串,但是您可以使用JSON.parse()JSON.stringify()来解决。实现可能看起来像这样(我急着写了这个,可能写得更短更好一些,但是应该可以用,我在注释中写了一些解释):

// Store javascript object to localStorage
Storage.prototype.setObject = function(key, value) {
    this.setItem(key, JSON.stringify(value));
}

// Get javascript object from localStorage
Storage.prototype.getObject = function(key) {
    return JSON.parse(this.getItem(key));
}

// Your URLs with default visited values
var urls = [
    { name: "somesite1", url: "http://somesite1.com", visited: false },
    { name: "somesite2", url: "http://somesite2.com", visited: false },
    { name: "somesite3", url: "http://somesite3.com", visited: false },
    { name: "somesite4", url: "http://somesite4.com", visited: false }
];

// If there's no urls object in localStorage, call setDefault method
if (!localStorage.getObject("urls")) {setDefault();}

// Check all link objects. If all are visited, return true, else return false
function checkVisited() {
    var counter = 0;
    var getUrls = localStorage.getObject("urls");
    for (var i = 0; i < getUrls.length; i++) {
        if (getUrls[i].visited) {counter++;}
    }
    return counter === getUrls.length;
}

// Set defaults values to localStorage
function setDefault() {
    localStorage.setObject("urls", urls);
}

// If all links are visited, set default values
// Then get random links until you find one
// that's not visited. When it's found, set it
// to visited in localStorage and redirect to it 
function goSomewhere() {
    if (checkVisited()) {setDefault();}
    var getUrls = localStorage.getObject("urls");
    var visited = true;
    while(visited) {
        var e = Math.floor(Math.random()*getUrls.length);
        if (!getUrls[e].visited) {
            visited = false;
            getUrls[e].visited = true;
            localStorage.setObject("urls", getUrls);
            window.location = getUrls[e].url;
        }
    }
}

希望这会有所帮助。要查看有关localStorage的更多信息,请查看MDN:https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

也适用于JSON:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON