Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

javascript - 如何获得eventListener“按键”来触发我的不同页面(学生项目)的链接?(How can I get an eventListener “keypress” to trigger links of my differents pages (student project)?)

I"m working on a school project, so I have some limitations (rules). I can just use basic html css and javascript. No libraries.(我正在做一个学校项目,因此有一些限制(规则)。我只能使用基本的HTML CSS和javascript。没有库。)

I set up 5 pages (including the index), and i wanted to create some functions on an keyboard event, so the user can navigate between the 5 pages with keyboard 1 to 5 keys.(我设置了5页(包括索引),并且希望在键盘事件上创建一些功能,以便用户可以使用键盘1至5键在5页之间导航。) Here are my html and js code so far, i'm pretty sure the window location href is the problem here.(到目前为止,这是我的html和js代码,我很确定窗口位置href是这里的问题。) It works, but its failing after 3 or 4 uses.(它可以工作,但是3或4次使用后失败。) function touche1(){ console.log("touche 1 tapée"); window.location.href = "../index.html"; } function touche2(){ console.log("touche 2 tapée"); window.location.href = "./pages/projets.html"; } function touche3(){ console.log("touche 3 tapée"); window.location.href = "./pages/presentation.html"; } function touche4(){ console.log("touche 4 tapée"); window.location.href = "./pages/medias.html"; } function touche5(){ console.log("touche 5 tapée"); window.location.href = "./pages/contact.html"; } document.addEventListener("keypress", function(e){ var touche = String.fromCharCode(e.charCode) switch(touche){ case "1": touche1() break; case "2": touche2() break; case "3": touche3() break; case "4": touche4() break; case "5": touche5() break; }}) <nav> <a href="../index.html">Accueil</a> <a href="./projets.html">Projets</a> <a href="./presentation.html">Présentation</a> <a href="./medias.html">médias</a> <a href="./contact.html" id="contact">Contact</a><br><br> </nav> I know it's linked to my pages url / window position href, but cant figure it out.(我知道它链接到我的页面url /窗口位置href,但是无法弄清楚。) thanks a lot :)(非常感谢 :))   ask by shogo translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try (open chrome console, run snippet and push keys 1-5)(尝试(打开Chrome控制台,运行代码段并按1-5键))

document.body.onkeypress = e => { let links = [ 'index.html', 'pages/projets.html', 'pages/presentation.html', 'pages/medias.html', 'pages/contact.html', ] location = links[e.key-1]||links[0]; } <nav> <a href="index.html">Accueil</a> <a href="pages/projets.html">Projets</a> <a href="pages/presentation.html">Présentation</a> <a href="pages/medias.html">médias</a> <a href="pages/contact.html" id="contact">Contact</a><br><br> </nav>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...