0

Possible Duplicate:
Javascript infamous Loop problem?

When a mousemove event is reaised the variable i is equal to last value(In my case = 4) for ALL sectors. Where i can store value of i?

for (var i = 0; i < pieChart.Sectors.length; i++) {
  pieChart.Sectors[i].mousemove(function (event) {
     var percent = (localData[i] * 100) / totalSum;
     pieChart.Popup(event.clientX, event.clientY, [percent, "% всего времени\n Было сделано", localData[i], "звонков"].join(' '));
  });
}
Community
  • 1
  • 1
Neir0
  • 12,079
  • 27
  • 80
  • 136

3 Answers3

1

You need a closure. See here for a nice explanation: http://www.mennovanslooten.nl/blog/post/62

I'll be posting your code modified shortly.

Mrchief
  • 73,270
  • 19
  • 138
  • 185
1

Answered like a thousand times, 1001 answers: Your event handler functions will close over the i variable. That means, all functions reference the same variable and therefore all of them have the identical value.

Solution: Introduce a new function(-context):

pieChart.Sectors[i].mousemove((function (myEvent) {
        return function() {
            var percent = (localData[i] * 100) / totalSum;
            // do something with "myEvent"
        };
}(event)));
jAndy
  • 223,102
  • 54
  • 301
  • 354
0

Check if you variable $i had been declared as a global variable before.

You can even check this with an alert(window.i); or console.log(window.i); at any time.

monsieur_h
  • 1,340
  • 1
  • 10
  • 20