Javascript语法混淆

时间:2020-05-06 07:28:48

标签: javascript dom dom-events

// 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,因为它只是重新定义了该函数(我不知道他指的是哪个函数重新定义)”

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

第一行将直接在鼠标按下时调用keyPlay,而第二行将创建一个函数,然后调用keyReturn。第二行实际上是错误的,因为事件未定义(您必须在函数的输入中声明它)。我喜欢第一行,因为它可以使代码保持整洁。