我制作了一个音板网站,其中有许多小音频剪辑和下面的 Javascript,可以在播放完毕后播放、暂停和重置它们。该页面完全按照预期工作,但我得到了
index.html:90 Uncaught TypeError: Cannot read property 'getAttribute' of null
我的 Javascript 控制台出错,我不知道为什么。
cliplist = ['audio1','audio2','audio3','audio4','audio5','audio6','audio7','audio8'];
playerlist = ['player1','player2','player3','player4','player5','player6','player7','player8'];
document.addEventListener("DOMContentLoaded", function()
{
for(let i=0;i<cliplist.length;i++)
{
document.getElementById(playerlist[i]).addEventListener("click", function()
{
playClip(cliplist[i]);
})
document.getElementById(playerlist[i]).addEventListener("click", function()
{
playClip(cliplist[i],playerlist[i]);
})
document.getElementById(cliplist[i]).addEventListener("ended", function()
{
reset(playerlist[i]);
})
}
});
function playClip(theclip,theplayer)
{
playerElement = document.getElementById(theplayer);
clipElement = document.getElementById(theclip)
if(playerElement.getAttribute("src") == 'playbutton.png')
{
playerElement.setAttribute("src","pausebutton.png");
clipElement.play();
}
else
{
playerElement.setAttribute("src","playbutton.png");
clipElement.pause();
}
}
function reset(theplayer)
{
document.getElementById(theplayer).src = 'playbutton.png';
}
最佳答案
您对 playClip
的调用如下所示:
playClip(cliplist[i]);
它只传递一个参数。但是,playClip()
需要第二个参数,这就是与 .getElementById()
一起使用的,它获取 .getAttribute()
的 DOM 元素code> 被调用。当您不传递参数时,您不会获得 DOM 元素,并且会收到错误。
因此,请确保向它传递它正在寻找的两个参数,就像您在其他地方写道的那样:
playClip(cliplist[i],playerlist[i]);
最后,它仍然有效的原因是您向 document.getElementById(playerlist[i])
添加了两个 click
事件处理程序。第一个抛出错误,第二个有效。
关于javascript - 未捕获类型错误 : Cannot read property 'getAttribute' of null but code is working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51992581/