问题描述
我的问题是。当我向下面的audioBoing函数添加参数,然后将相同的参数放入getElementById字符串中时,该函数不起作用。我收到一个错误,提示未捕获类型错误,无法调用Null的方法‘AddEventListener’
下面的函数运行正常。我重写了它下面的函数,以反映我正在尝试做的事情。最终,我试图抽象该函数的一大部分,这样我就可以插入参数并运行它,而不必每次为它存储/启动的每个声音重写它。
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();
重写的非工作
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);
推荐答案
您没有将传递给audioBoing的字符串引起来
audioBoing("noteOneDrumOneBig");