0

I'm breaking my head here. I have this Javascript code:

var myPath = {};
for (var i = 0; i < myData.length; i++) {
    myPath[myData[i].CodigoEvento].row = {
                    elem: $("<tr>").appendTo($("#TablaMoviles tbody")).hover(function () {
                        console.log(i);
                    }, function () {
                        console.log(i);
                    })
                }
}

It is suposed to iterarte a data array (myData) and for each item, create a row in a table using JQuery. That works perfect. The problem is when I create the hover event and try to print the index of the row pointed by the mouse(i). Instead of give my row number, it always show the last index of the array.

What am I missing here?

thanks

Dave Sexton
  • 10,768
  • 3
  • 42
  • 56
ericpap
  • 2,917
  • 5
  • 33
  • 52
  • I think it's because the variable `i` is the last index from your for-loop and when you trigger the `hover`event, you actually read the value of `i`, which is ofcourse the last index. If that makes any sense, I'm not quite sure about my theory. If anyone can confirm this? – Jorrex Jan 08 '16 at 14:38
  • Yes, something like that. What @ericpap needs is a _closure_. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures – beercohol Jan 08 '16 at 14:43
  • You could change the `console.log(i);` to `console.log($(this).index())`, that will give you the index of the row you are hovering over – Jorrex Jan 08 '16 at 14:44

0 Answers0