问题
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