开发者

Problem with loop [duplicate]

This question already has answers here: 开发者_Python百科 Closed 11 years ago.

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


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜