4

HTML

<body>
    <div id='test' onClick="load()">
       2
    </div>
</body>

Javascript

load = function() {
  test.innerHTML = "";

    for (var i = 0; i < 5; i++) {

        var p = document.createElement("p");
        p.innerHTML = "Link";

        p.onclick = function () {
            alert("LINK NR: " + i)
        }

        document.getElementById('test').appendChild(p);

    }
}

In the code above, why does the function always return the last value?

Here is a fiddle for the code.

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
Jacob
  • 3,580
  • 22
  • 82
  • 146
  • 2
    `i` is not pinned within the event function, see [Javascript closure inside loops - simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Alex K. Aug 30 '13 at 12:13

4 Answers4

5

The p.onclick function is only going to be called whenever there is a "click" event fired on the element and by then the value of i would be 5 as the loop had already finished executing by that time.

What you are expecting that the function statement will be executed for each loop iteration - that is not the case. If it was indeed executed, then for each iteration you would have got an alert message, irrespective of element was clicked or not.

This can be checked by keeping a console.log outside and inside the function and you will find for each iteration the console.log statement outside the function will be printed in your browser's console but the console.log statement inside function will not be executed for each iteration of the loop.

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
Vinod Louis
  • 4,812
  • 1
  • 25
  • 46
1

Try this:

    (function(i){
        p.onclick = function () {
            alert("LINK NR: " + i)
        }
    })(i);

Fiddle: http://jsfiddle.net/sFXep/2/

Here is the explanation: http://en.wikipedia.org/wiki/Immediately-invoked_function_expression

And here: http://benalman.com/news/2010/11/immediately-invoked-function-expression/

Ivan Chernykh
  • 41,617
  • 13
  • 134
  • 146
1
check this  fiddle  link i have made some small changes

http://jsfiddle.net/sFXep/8/

Man Programmer
  • 5,300
  • 2
  • 21
  • 21
  • It's better to provide some information of what these changes do in the answer - as well, links can "rot" over time, leaving answers such as these useless - see [Meta Stack Overflow](http://meta.stackexchange.com/questions/84342/answer-that-only-contains-a-link-to-jsfiddle). Also, `this type of thing` is not meant for highlighting text - you have other methods such as quotes, bold, italic text and lists to be able to get your point across. – Qantas 94 Heavy Aug 30 '13 at 12:22
1

Once the for statement executed completely the local variable i has value 5.
And in all created event handlers the i is the same as the final value of i in the for loop

frogatto
  • 28,539
  • 11
  • 83
  • 129