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,849
  • 28
  • 83
  • 139

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
  • 75,126
  • 20
  • 142
  • 189
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
  • 231,737
  • 57
  • 305
  • 359
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,360
  • 1
  • 10
  • 20