首页 > 解决方案 > Javascript在函数中增加一个变量

问题描述

嘿伙计们,我是编程新手,我需要为学校制作一个网站。我想在按箭头键时打开下一页。所以我想,当按下按钮时,我可以将 URL 放入一个数组中并增加索引。不幸的是,当我按下向下键时,我得到了一些从 1 到 3 的随机数。

const url = ['/#t1', '/#t2', '/#t3', './contact.html', './404.html'];

var index = 0;

$(document).keydown(function(e) {
    switch(e.which) {
       case 38: // up
           up();
       break;

       case 40: // down
           down();
       break;

       default: return; 
   }
   e.preventDefault();
});

function up() {
    index = index - 1;
    alert(index);
    window.location.href = url[index];
}

function down() {
    index = index + 1;
    alert(index);
    window.location.href = url[index];
}

标签: javascriptarraysfunctionswitch-statementincrement

解决方案


在不使用存储的情况下解决此问题的一种快速方法是在数组中查找索引,而不是跟踪它。你可以这样做:

const url = ['/list', '/of', '/urls'];

//find index of current url in array
let index = url.indexOf(window.location.pathname)

if(index == -1){
 //url is not in the array
 windows.alert("invalid url")
}

编辑:我同意 Michael Geary 的观点,这对于现实世界的网站来说是个坏主意


推荐阅读