随机链接javascript忽略当前页面

时间:2016-04-07 20:20:45

标签: javascript jquery twitter-bootstrap navigation navbar

当我点击'随机'我的导航栏上的链接(bootstrap)它指的是我的模拟网站上的随机页面的Javascript代码(下面)。

但是我想添加一个功能,所以如果我开始说Link[2]=fed-rates.html,当我按下'随机'链接在我的导航栏上它总是让我离开我目前所在的页面(也就是说,它忽略了链接[2])。

我想知道这是否可行,想得到一些想法会很棒。

Javascript代码:

function randomlinks(){
    var myrandom=Math.round(Math.random()*2)
    var links=new Array()
    links[0]="articles/how-to-trade-oil.html"
    links[1]="articles/usd-yen-gbp.html"
    links[2]="articles/fed-rates.html"

    window.location=links[myrandom]
}

// above is for all web pages

function randomlinksarticle(){
    var myrandom=Math.round(Math.random()*2)
    var links=new Array()
    links[0]="how-to-trade-oil.html"
    links[1]="usd-yen-gbp.html"
    links[2]="fed-rates.html"

    window.location=links[myrandom]
}

// above is so navbar link still works on the linked pages, with the way I have the folder directory setup

提出的新代码" / undefined"页:

function randomlinksarticle(){
var myrandom=Math.round(Math.random()*2)
var links=new Array()
links[0]="how-to-trade-oil.html"
links[1]="usd-yen-gbp.html"
links[2]="fed-rates.html"

links.forEach(function(link, index) {
if (location.href.indexOf(link) !== -1) {
    links.splice(index, 1);
}});
window.location=links[myrandom]

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

links.forEach(function(link, index) {
    if (location.href.indexOf(link) !== -1) {
        links.splice(index, 1);
    }
});

查看所有链接并检查它们是否存在于当前URL中。如果是这样,它会使用拼接功能将它们从列表中删除。

设置链接[2]后添加此代码,因为它应该删除当前页面。

编辑:我也注意到你的随机函数没有均匀分布。这并不重要,但它可能会给你带来麻烦。这样做的原因是0到2之间有更多的数字,它们会变为1而不是0或2。为了从随机数字刻度中得到零,Math.random()必须小于0.5。同样,它必须大于或等于1.5才能得到2.你对0和2有0.5 / 2或1/4的概率。这样就得到了1/2的概率,这是有意义的,因为所有的数字介于0.5和1.5之间会给你1。

tl; dr:使用math.floor(Math.random() * (maximum + 1))而不是Math.round(Math.random() * maximum)来生成随机数。

另外,如果你想要一种重复性较低的方法来做这件事,你可以用这两种函数代替:

function randomLink() {
    var links = Array.prototype.slice.call(arguments, 0); //Turns the function's arguments into an array
    links.forEach(function(link, index) { //Loops through all the links
        if (location.href.indexOf(link) !== -1) { //If the link text is contained in the url
            links.splice(index, 1); //Remove the link from the links array
        }
    });
    var rand = Math.floor(Math.random() * links.length); //Choose a number between 0 and links.length - 1
    window.location = links[rand]; //Visit the link
}

你可以像randomLink("first_page.html", "second_page.html")那样用任意数量的页面来调用它。