提取匿名函数

时间:2017-06-17 18:07:36

标签: javascript

CodePen

在第19行,事件监听器调用一个匿名函数,我想将其分解为自己的函数,但我也认为我需要传递第三个参数。可能是padz类,或者也许是音频标签..可能是两者的组合,但不确定这样做的语法。

的JavaScript

var clickCounter = 0;
var currentLevel = 0;
var simon_sSequence = [];
var player_sInput = [];
const audioTapper = document.querySelector("#audioT");
const audioError = document.querySelector("#audioE");
const levelDisplay = document.getElementById("level_Display");
const simonzSequence = document.getElementById("simon_sSequence");
const playerInput = document.getElementById("player_sInput");
const start_Tapper = document.querySelector(".startTapper");
const pads = document.querySelectorAll(".padz");
// Convert the padz list to an array that we can iterate over using .forEach()
Array.from(pads).forEach((pad, index) => {
  // Get the associated audio element nested in the padz-div
  const audio = pad.querySelector("audio");
  // Add a click listener to each pad which
  // will play the audio, push the index to
  // the user input array, and update the span
  pad.addEventListener("click", () => {
    player_sInput.push(index);
    if (player_sInput[clickCounter] !== simon_sSequence[clickCounter]) {
      audioError.play();
      $("body").animate({ backgroundColor: "red" }, 100);
      $("#container").effect( "shake", {times:100}, 1000, 'linear' );
      $("body").animate({ backgroundColor: "gray" }, 5000);
      //console.log("wrong");
    } else {  //end of if
      audio.play();
      playerInput.textContent = "Player's reply " + player_sInput;
      clickCounter++;
        //console.log(clickCounter);
    }   //end of else
  });   //end of EventListener
});     //end of Array.from(pads).forEach((pad, index)
start_Tapper.addEventListener("click", (resetStart)); //end of EventListener
function resetStart() {
  //generate a random number & push it to simon_sSequence
  simon_sSequence.push(Math.floor(Math.random() * 4));
  simonzSequence.textContent = "Simon says " + simon_sSequence;
  playerInput.textContent = "Player's reply " + player_sInput;
  //for each in the array set time interval(300ms);
  //dipslay hover effect
  //play pad sound
  audioTapper.play();
  player_sInput = []; //clear player's input for this turn
  clickCounter = 0;
  currentLevel++;
  levelDisplay.textContent = "Level: " + currentLevel + " " + simon_sSequence.length + " " + player_sInput.length;
}

0 个答案:

没有答案