Can't pass a DOM element to a constructor function in Javascript when trying to abstract section of WebAudio API xhr request

有些话、适合烂在心里 提交于 2019-12-11 14:33:45

问题


My problem is this. When I add an argument to the audioBoing function below and then place the same argument in the getElementById string, the function doesn't work. I get an error that says uncaught type error, cannot call method 'AddEventListener' of null

The function below works fine. I rewrote the function below it to reflect what I'm trying to do. Ultimately I am trying to abstract a good portion of the function so I can just plug in arguments and run it without having to rewrite it each time for each sound it stores / launches.

var playAudioFileOneDrumOneBig = function () {
var source = context.createBufferSource();
source.buffer = savedBufferOne;
source.connect(delay.input);
delay.connect(convolver.input);
convolver.connect(context.destination);
source.noteOn(0); // Play sound immediately
};




function audioBoing()  
var xhr = new XMLHttpRequest();
xhr.open('get', 'audio/F.mp3', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function () {
        context.decodeAudioData(xhr.response,
             function(incomingBuffer1) {
                 savedBufferOne = incomingBuffer1;
                 var noteOneDrumOneBig = document.getElementById("noteOneDrumOneBig"); 
                 noteOneDrumOneBig.addEventListener("click", playAudioFileOneDrumOneBig , false);
             }
        );
};
xhr.send();
};

audioBoing();

ReWritten non-working

function audioBoing(yay) {      //added yay

this.yay=yay;                 // defined yay

var xhr = new XMLHttpRequest(); 
xhr.open('get', 'audio/F.mp3', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function () {
        context.decodeAudioData(xhr.response,
             function(incomingBuffer1) {                  
                 savedBufferOne = incomingBuffer1;    
                 var noteOneDrumOneBig = document.getElementById(yay);           //passed yay
                 noteOneDrumOneBig.addEventListener("click", playAudioFileOneDrumOneBig , false);   //error happens here
             }
        );
};
xhr.send();
};

audioBoing(noteOneDrumOneBig);

回答1:


You didn't quote the string you passed to audioBoing

audioBoing("noteOneDrumOneBig");


来源:https://stackoverflow.com/questions/13560218/cant-pass-a-dom-element-to-a-constructor-function-in-javascript-when-trying-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!