JavaScript 中未定义的参数

问题描述 投票:0回答:1

以下 JS 代码可启用演示鼓套件:

var numberOfdrumButtons = document.querySelectorAll(".drum").length;
// call 2 functions when the click-event is triggered
for (var i = 0; i < numberOfdrumButtons; i++) {
    document.querySelectorAll(".drum")[i].addEventListener("click", function (){

    var buttonInnerHTML = this.innerHTML;

    makeSound(buttonInnerHTML);
    buttonAnimation(buttonInnerHTML);    

    });
}
// call 2 functions when the keydown-event is triggered
document.addEventListener("keydown", function(event){

    makeSound(event.key);
    buttonAnimation(event.key);    

  
});
//function to make sound
function makeSound(key){

    switch (key) {
        case "w":
            var audio = new Audio("sounds/crash.mp3");
            audio.play();
        case "a":
            var audio = new Audio("sounds/kick-bass.mp3");
            audio.play();
        case "s":
            var audio = new Audio("sounds/snare.mp3");
            audio.play();
        case "d":
            var audio = new Audio("sounds/tom-1.mp3");
            audio.play();
        case "j":
            var audio = new Audio("sounds/tom-2.mp3");
            audio.play();
        case "k":
            var audio = new Audio("sounds/tom-3.mp3");
            audio.play();
        case "l":
            var audio = new Audio("sounds/tom-4.mp3");
            audio.play();
        
            
            break;
       
        default:
            break;

       }

    }
//function to add an animation
function buttonAnimation(currentKey){

    var activeButton = document.querySelector("." + currentKey);
    activeButton.classList.add("pressed");
    setTimeout(function() {
        activeButton.classList.remove("pressed");
    }, 100
    
    )

}

所以我的问题是关于函数

currentKey
中的
buttonAnimation
参数。它从何而来?如果之前没有定义它如何发挥作用?它是如何工作的?我在另一个 JS 练习中偶然发现了同样的值,但我不知道。该参数称为
currentColor

我尝试使用事件作为参数,但功能

buttonAnimation(currentKey)
不起作用。具体来说,setTimeout 函数当时不起作用。

javascript button undefined settimeout event-listener
1个回答
0
投票

代码的组织是这一切的关键。您首先调用尚未定义的函数。

for (var i = 0; i < numberOfdrumButtons; i++) {
    document.querySelectorAll(".drum")[i].addEventListener("click", function (){

    var buttonInnerHTML = this.innerHTML;

    makeSound(buttonInnerHTML);
    buttonAnimation(buttonInnerHTML);    

    });
}

通过调用

makeSound ( buttonInnerHTML )
buttonAnimation ( buttonInnerHTML )
,您可以添加 buttonInnerHTML 作为参数 函数buttonAnimation

//function to add an animation
function buttonAnimation(currentKey){

    var activeButton = document.querySelector("." + currentKey);
    activeButton.classList.add("pressed");
    setTimeout(function() {
        activeButton.classList.remove("pressed");
    }, 100
    
    )

}

请注意,currentKey只是一个被buttonInnerHTML参数或event.key参数替换的参数。当尝试理解逻辑或调试时,组织代码可能会派上用场。

© www.soinside.com 2019 - 2024. All rights reserved.