Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Javascript functions dynamically [duplicate]

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.

like image 693
Jacob Avatar asked Feb 15 '23 10:02

Jacob


1 Answers

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.

like image 53
Vinod Louis Avatar answered Feb 24 '23 03:02

Vinod Louis