// The keys and notes variables store the piano keys
const keys = ['c-key', 'd-key', 'e-key', 'f-key', 'g-key', 'a-key', 'b-key',
'high-c-key', 'c-sharp-key', 'd-sharp-key', 'f-sharp-key', 'g-sharp-key', 'a-
sharp-key'];
const notes = [];
keys.forEach(function(key){
notes.push(document.getElementById(key));
})
// Write named functions that change the color of the keys below
const keyPlay = function(event){
event.target.style.backgroundColor = "#ababab";
}
const keyReturn = function(event){
event.target.style.backgroundColor = "";
}
// Write a named function with event handler properties
function eventAssignment(note){
note.onmousedown = keyPlay;
note.onmouseup = function(){
keyReturn(event);
}
}
// Write a loop that runs the array elements through the function
notes.forEach(eventAssignment);
LINE-17 和 LINE-18 通过触发事件处理程序来实现类似的目的,讲师告诉我不要在 LINE-17 中使用此语法,即使它工作得很好。他提到了一些完全在我脑海中跳跃的东西“我们不能将 note.onmousedown
定义为 keyPlay
函数,因为它只会重新定义该函数(我不知道他指的是哪个函数被重新定义)”
如有任何帮助,我们将不胜感激。
最佳答案
第一行将在鼠标按下时直接调用 keyPlay,同时第二行将创建一个函数,然后调用 keyReturn。第二行实际上是错误的,因为事件未定义(您必须在函数的输入中声明它)。我更喜欢第一行,因为它可以使代码保持简洁。
关于JavaScript 语法困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61629629/