admin管理员组文章数量:1310431
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?
1 Answer
Reset to default 11goAlbum
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.
本文标签: javascriptaddEventListener click executed before clickedStack Overflow
版权声明:本文标题:javascript - addEventListener click executed before clicked - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741830785a2399916.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论