0

I have a set of circles in the childCircles array. I tried to add listeners using nested functions. However, all events are fired and I end up getting only the last result.

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

console message when only one circle is clicked:

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

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • 1
    What's contained in your `childCircle` array, and `inner` function? Seeing a working example would really help here. Note that by using `inner(i)` you're immediately calling that function and assigning its result to the click handler. – Rory McCrossan Jun 04 '15 at 07:04
  • The childCircle array actually contains div elements. The inner function is already in the code. – Ayush Mukherjee Jun 04 '15 at 13:13

0 Answers0