无法读取未定义的属性“ innerText”?代码结构说明必填

时间:2019-05-22 20:04:45

标签: javascript

这是问题所在:我有7个按钮,其中必须添加事件侦听器,该事件侦听器将响应单击并在单击任何按钮时播放相应的声音。我使用querySelectorAll()方法选择所有这些类,并使用循环将事件侦听器添加到所有这些按钮,但是由于开关盒表达式(例如drumArray [i] .innerText)中的某些问题,音频无法播放,我想获得错误原因及原因。我的意思是像switch语句由于该错误而终止一样。

我知道可以使用this.innerText来解决切换案例表达式,但是我想知道为什么以下drumArray [i] .innerText无效!

var drumArray = document.querySelectorAll('.drum');

for (var i = 0; i < drumArray.length; i++) {
  drumArray[i].addEventListener("click", function() {

    switch (drumArray[i].innerText) { //Problem here
      case "w":
        var drumAudio = new Audio('./sounds/tom-1.mp3');
        drumAudio.play();
        break;
      case "a":
        var drumAudio1 = new Audio('./sounds/tom-2.mp3');
        drumAudio1.play();
        break;
      case "s":
        var drumAudio2 = new Audio('./sounds/tom-3.mp3');
        drumAudio2.play();
        break;
      case "d":
        var drumAudio3 = new Audio('./sounds/tom-4.mp3');
        drumAudio3.play();
        break;
      case "j":
        var drumAudio4 = new Audio('./sounds/snare.mp3');
        drumAudio4.play();
        break;
      case "k":
        var drumAudio5 = new Audio('./sounds/crash.mp3');
        drumAudio5.play();
        break;
      case "l":
        var drumAudio6 = new Audio('./sounds/kick-bass.mp3');
        drumAudio6.play();
        break;
    }

  });
}

1 个答案:

答案 0 :(得分:0)

您正在将click分配给按钮,因此您需要输入EventArgs

我们在这里添加了e,这将使您可以使用e.target-在这种情况下,您的按钮是

var drumArray = document.querySelectorAll('.drum');

for (var i = 0; i < drumArray.length; i++) {
  drumArray[i].addEventListener("click", function(e) {
    // e is the event.
    // target is the item clicked.
    switch (e.target.innerText) { //Problem here
      case "w":
        var drumAudio = new Audio('./sounds/tom-1.mp3');
        drumAudio.play();
        break;
      case "a":
        var drumAudio1 = new Audio('./sounds/tom-2.mp3');
        drumAudio1.play();
        break;
      case "s":
        var drumAudio2 = new Audio('./sounds/tom-3.mp3');
        drumAudio2.play();
        break;
      case "d":
        var drumAudio3 = new Audio('./sounds/tom-4.mp3');
        drumAudio3.play();
        break;
      case "j":
        var drumAudio4 = new Audio('./sounds/snare.mp3');
        drumAudio4.play();
        break;
      case "k":
        var drumAudio5 = new Audio('./sounds/crash.mp3');
        drumAudio5.play();
        break;
      case "l":
        var drumAudio6 = new Audio('./sounds/kick-bass.mp3');
        drumAudio6.play();
        break;
    }

  });
}