为什么没有定义getAttribute?

时间:2017-07-26 15:01:37

标签: javascript properties

我有这个脚本,我正在运行。它显示在第164行未定义getAttribute属性。我不明白为什么。我已经尝试回溯各种函数调用以寻找中断,但我没有看到它

Look for Album.js file

1 个答案:

答案 0 :(得分:0)

您的mouseleave事件监听器总是会event.target.className album-view-song-item因为songRows被定义为document.getElementsByClassName("album-view-song-item");

因此,在侦听器中调用getSongItem(event.target)时:

songRows[i].addEventListener("mouseleave", function(event) {
    var songItem = getSongItem(event.target);
    var songItemNumber = songItem.getAttribute("data-song-number");

    if (songItemNumber !== currentlyPlayingSong){
        songItem.innerHTML = songItemNumber;
    }
});

element.classNamealbum-view-song-item。当这被传递到你的函数时:

var getSongItem = function(element){
    switch(element.className){
        case "album-song-button":
        case "ion-play":
        case "ion-pause":
            return findParentByClassName(element, "song-item-number");
        case "song-item-title":
        case "song-item-duration":
            return findParentByClassName(element, "album-view-song-item").querySelector(".song-item-number");
        case "song-item-number": 
            return  element;
        default:
            return;
    }
};

这将落到default的情况,返回undefined。如您所见,在未定义的情况下调用getAttribute会向您显示错误Cannot read property 'getAttribute' of undefined