最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - addEventListener click executed before clicked - Stack Overflow

programmeradmin0浏览0评论

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 executed when it is created, and then the function won't execute anymore. What am I doing wrong?

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 executed when it is created, and then the function won't execute anymore. What am I doing wrong?

Share Improve this question edited Jan 11, 2022 at 18:29 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Dec 2, 2014 at 8:34 goggelzgoggelz 931 silver badge6 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 11

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.

发布评论

评论列表(0)

  1. 暂无评论