javascript - 未捕获类型错误 : Cannot read property 'getAttribute' of null but code is working

标签 javascript html

我制作了一个音板网站,其中有许多小音频剪辑和下面的 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/

相关文章:

html - chrome 中的 Chrome css3 混合混合模式错误

html - 边界问题和流畅的布局

javascript - 构建内容不同的函数的工厂?

javascript - API Connect 网关脚本中的 AES 加密解密 JSON Datapower

html - 在html中的ol中的数字前插入一个元素

javascript - jQuery 的 .val() 在 Firefox 和 Chrome 中为带有占位符文本的输入元素返回不同的值

javascript - 谷歌地图标记点击并拖动特定缩放级别

javascript - 如何将等式中的多项式项移到一边?

javascript - 添加事件监听器 对于按下的任何字母键?

html - CSS: "height: 100%;"有效,但会破坏正常流程