addEventListener click executed before clicked

爷,独闯天下 提交于 2020-01-02 07:25:12

问题


I want to pass over parameters in the click function.

var albums = document.getElementsByClassName("album");
for(var i = 0; i<albums.length; i++){
    document.getElementById(albums[i].id).addEventListener("click", goAlbum(albums[i].id), false);
}

however, the function "goAlbum" gets excecuted when it is created, and then the function won't excecute anymore. what am I doing wrong?


回答1:


goAlbum was getting executed because you called the function. You weren't "creating" a function. What you intended to do was supply addEventListener with logic to execute when something is clicked; that logic being "invoke goAlbum". To do this, wrap the function call in an anonymous function.

function toArray(list) {
    return Array.prototype.slice.call(list);
}

var albums = toArray(document.getElementsByClassName("album"));
albums.forEach(function (album) {
    document.getElementById(album.id).addEventListener("click", function () {
        goAlbum(album.id);
    }, false);
});

Additionally, because it is unwise to create functions in a for loop, I have refactored your code to use forEach. I need to convert the NodeList returned by document.getElementsByClassName to an Array in order to use forEach, hence the toArray function.



来源:https://stackoverflow.com/questions/27245040/addeventlistener-click-executed-before-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!