for循环中HTML集合的事件侦听器和闭包

时间:2016-02-19 10:25:31

标签: javascript for-loop closures htmlcollection

代码是

//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))
}

但输出仍然相同。所以有两个问题:

1)如果我没有调用该函数,为什么控制台输出包含七个处理程序调用的结果,只是将其设置为处理程序?

2)如何在&#34; for&#34;中设置处理程序? HTML集合的循环?

2 个答案:

答案 0 :(得分:0)

您必须使用关闭

var artists = document.getElementsByClassName("gallery")[0].getElementsByTagName("img");
for (var i = 0; i < artists.length; i++) {
    artists[i].addEventListener("click", function(index) {
        return function() {
            //You can use index for the current clicked item index
            // console.log(index);
            var artistPhoto = document.getElementsByClassName("artist-photo")[0];
            var artistBio = document.getElementsByClassName("artist-bio")[0];

            var i = this.getAttribute("src").indexOf(".jpg");
            var photoName = this.getAttribute("src").slice (0, i);

            artistPhoto.style.background="url(" + photoName + "-large.jpg";
            console.log("it happened");

        }
    }(i));
}

答案 1 :(得分:0)

$('body *').on('mouseover',function(){console.log(this.tagName)});

$('body *')选择体内的所有元素。