Javascript 如何在用户每次单击按钮时按顺序向下查看链接列表?

Javascript 如何在用户每次单击按钮时按顺序向下查看链接列表?,javascript,html,arrays,Javascript,Html,Arrays,我从激活onclick功能的按钮开始: <button onclick="openStuff();">Click here!</button> 最后,我定义了一个函数,该函数随机将链接应用于上述数组中的按钮: openStuff = function () { // get a random number between 0 and the number of links var randIdx = Math.random() * l

我从激活onclick功能的按钮开始:

<button onclick="openStuff();">Click here!</button>
最后,我定义了一个函数,该函数随机将链接应用于上述数组中的按钮:

openStuff = function () {
    // get a random number between 0 and the number of links
    var randIdx = Math.random() * links.length;
    
    // round it, so it can be used as array index
    randIdx = parseInt(randIdx, 10);

    // construct the link to be opened
    var link = 'https://' + links[randIdx];

    // open it in a new window / tab (depends on browser setting)
    window.open(link);
};
问题是我需要它不是随机的。相反,我需要它在用户单击按钮时按顺序进入列表。如果用户单击按钮一次,则应转到第一个链接。但是,如果该用户再次单击按钮,则应转到列表中的第二个链接


例如:用户单击按钮:转到第一个链接,用户再次单击按钮:转到第二个链接,依此类推。

您需要一个从0开始的全局索引。然后,在函数内部,在打开链接后将其递增

var link = 'https://' + links[index];
index++;

我会这样做:

var特殊按钮状态=0;
常量链接=[
“msn.com”,
“google.com”,
“youtube.com”,
“bbc.com”,
“facebook.com”,
“cnn.com”,
“福克斯网”,
“techcrunch.com”
];
const openStuff=函数(){
var link='https://'+链接[特殊按钮状态];
if(特殊按钮状态
点击这里
var linkIndex=0;
openStuff=函数(){
//当没有更多链接可用时,单击“返回”

如果(links.length可以将另一个变量设置为数组的第一个索引,类似于:

var linkTarget = 0
然后在函数中更新linkTarget以适当增加:

openStuff = function () {
    // construct the link to be opened
    var link = 'https://' + links[linkTarget];

    // open it in a new window / tab (depends on browser setting)
    window.open(link);

    // update the index
    if (linkTarget++ == links.length)
        linkTarget = 0
};

您还可以实现一个动态标签,以便知道它的去向:

<body onload="setLink()">
    <button id="turntable-button" onclick="openStuff()" />
</body>
openStuff = function () {
    // construct the link to be opened
    var link = 'https://' + links[linkTarget];

    // open it in a new window / tab (depends on browser setting)
    window.open(link);

    // update the index
    if (linkTarget++ == links.length)
        linkTarget = 0
};
<body onload="setLink()">
    <button id="turntable-button" onclick="openStuff()" />
</body>
setLink = function() {
    document.getElementById("turntable-button").innerHTML = links[linkTarget];
}