所有事件处理程序都触发了Javascript循环

时间:2015-06-04 07:03:06

标签: javascript jquery html5 javascript-events

我在childCircles数组中有一组圆圈。我尝试使用嵌套函数添加侦听器。但是,所有事件都被触发,我最终只得到最后的结果。

var listenEvents = function() {
var topRow = document.getElementById('top-row');
var topRowBackground = document.getElementById('top-row-background');
var topRowIcon = document.getElementById('top-row-icon');
var images = ["http://placehold.it/1920x50","http://placehold.it/1920x49","http://placehold.it/1919x50","http://placehold.it/1919x49","http://placehold.it/1920x48","http://placehold.it/1918x50"];

for(var i = 0; i < childCircle.length; i++) {
    function inner(i) {
        return function() {
            console.log(event);
            console.log(i);
            topRowBackground.src = images[i];
            topRowIcon.src = $(childCircle[i]).children('img').attr("src");
            console.log(topRowBackground.src);
            console.log(topRowIcon.src);
            topRow.style.display = "block";
        }
    }

    $(document).on('click', childCircle[i], inner(i));
}
  单击一个圆圈时

控制台消息:

     

MouseEvent {}

     

0

     

http://placehold.it/1920x50

     

http://placehold.it/150x150

     

MouseEvent {}

     

1

     

http://placehold.it/1920x49

     

http://placehold.it/150x150

     

MouseEvent {}

     

2

     

http://placehold.it/1919x50

     

http://placehold.it/150x150

     

MouseEvent {}

     

3

     

http://placehold.it/1919x49

     

http://placehold.it/150x150

     

MouseEvent {}

     

4

     

http://placehold.it/1920x48

     

http://placehold.it/150x150

     

MouseEvent {}

     

5

     

http://placehold.it/1918x50

     

http://placehold.it/150x150

0 个答案:

没有答案