javascript - 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];
}
解决方案
在不使用存储的情况下解决此问题的一种快速方法是在数组中查找索引,而不是跟踪它。你可以这样做:
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 的观点,这对于现实世界的网站来说是个坏主意
推荐阅读
- python - 搜索单个项目的 3D 列表
- c# - 无法创建发布配置文件 - Azure
- font-awesome - Laravel 8 FontAwesome 不正确的目录
- python - tkinter 中的 python 视频流
- assembly - 汇编 8086 字符串到数字的转换
- java - 一台服务器上的 React.JS 应用程序和第二台服务器上的 Java API、Ubuntu、Apache Tomcat 9 Web 服务器
- reactjs - 无法覆盖模态组件中的样式?
- asp.net-core - 使用 Microsoft.Identity.Web 对 WebApp+API 的用户进行身份验证,以及如何管理生命周期
- javascript - 是否可以悬停按钮并显示图像?
- list - 键入'_InternalLinkedHashMap
' 不是类型 'List 的子类型