【发布时间】:2021-08-13 08:28:11
【问题描述】:
完全初学者问题就在这里。一个月前开始学习前端开发,现在我已经接触了 Javascript,开始着手我的第一个实践项目。在这种情况下,我想创建一个非常简单的吉他调音器,您可以在其中单击一个按钮并执行其对应的字符串。
这是我到目前为止得到的,但无法表达如何获取点击按钮的 id。而且,不知道如何在单击另一个按钮时结束一个音符的循环。
const keyS = document.addEventListener('keydown', function(e){
(e.key === 'd') ? this.getElementById ("string6").play()
:(e.key === 'f') ? this.getElementById ("string5").play()
:(e.key === 'g') ? this.getElementById ("string4").play()
:(e.key === 'j') ? this.getElementById ("string3").play()
:(e.key === 'k') ? this.getElementById ("string2").play()
:(e.key === 'l') ? this.getElementById ("string1").play()
: alert("That's not a valid key!")
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles/main.css">
<title>Guitar Tuner</title>
<script src="scripts/main.js"></script>
</head>
<body>
<ul>
<li><audio id="string" src="sounds/string6.mp3" type="audio/mpeg" controls loop></audio></li>
<li><audio id="string5" src="sounds/string5.mp3" type="audio/mpeg" controls loop></audio></li>
<li><audio id="string4" src="sounds/string4.mp3" type="audio/mpeg" controls loop></audio></li>
<li><audio id="string3" src="sounds/string3.mp3" type="audio/mpeg" controls loop></audio></li>
<li><audio id="string2" src="sounds/string2.mp3" type="audio/mpeg" controls loop></audio></li>
<li><audio id="string1" src="sounds/string1.mp3" type="audio/mpeg" controls loop></audio></li>
<br>
<button onclick="clickNote()">6th String</button>
<button onclick="clickNote()">5th String</button>
<button onclick="clickNote()">4th String</button>
<button onclick="clickNote()">3rd String</button>
<button onclick="clickNote()">2nd String</button>
<button onclick="clickNote()">1st String</button>
</ul>
</body>
</html>
我知道这可能是一个非常愚蠢的问题,但我想了解它是如何正常工作的,然后开始摆弄它。
提前感谢大家,非常欢迎任何 JS 学习或前端职业发展技巧!
P.S:请您原谅任何语法错误,因为英语不是我的母语。
【问题讨论】:
-
您需要在按钮单击时播放正确的声音吗?如果我点击 d f j g k l 按钮点击声音播放
-
关于如何获取被点击元素的id - stackoverflow.com/q/30786154/853295
-
拥有一个音频元素并使用该元素播放所有声音可能会更简单。您可以根据按下的按钮设置其来源。停止它很容易,因为您只需播放下一个声音,它就会停止前一个声音。
-
您还可以将参数传递给您的
clickNote()函数。可能是注释,例如clickNote("a")或索引,例如clickNote(1)。在您的 html 中,只需使用所需的参数调用函数,例如<button onclick="clickNote('a')">。只要您正确填充值,这将告诉您单击了哪个按钮。 -
How to get the id of the clicked button。从您的代码来看,虽然看起来您正在使用按键 - here's how to detect which key was pressed。
标签: javascript html