コードは
//Logic which works when the desired element is clicked
function changeArtistPhotoAndBio(prop) {
var artistPhoto = document.getElementsByClassName("artist-photo")[0];
var artistBio = document.getElementsByClassName("artist-bio")[0];
var i = prop.getAttribute("src").indexOf(".jpg");
var photoName = prop.getAttribute("src").slice (0, i);
artistPhoto.style.background="url(" + photoName + "-large.jpg";
console.log("it happened");
};
//Setting listeners for the click event in the loop
var artists = document.getElementsByClassName("gallery")[0].getElementsByTagName("img");
for (var i = 0; i < artists.length; i++) {
artists[i].addEventListener("click", changeArtistPhotoAndBio(artists[i]));
}
そして、コンソール出力は
7x it happened
また、クリック機能のイベント ハンドラーが機能しません。次のように、クロージャーでハンドラーを分離しようとしました。
for (var i = 0; i < artists.length; i++) {(function(i) {
artists[i].addEventListener("click", changeArtistPhotoAndBio(artists[i]));
}(i))
}
しかし、出力は同じです。したがって、2 つの質問があります。
1) 関数を呼び出さずにハンドラーとして設定した場合、コンソール出力に 7 つのハンドラー呼び出しの結果が含まれるのはなぜですか?
2) HTML コレクションの「for」ループでハンドラーを設定するにはどうすればよいですか?