0

Hello,

i have problem with an alert event to show the current link id. but that is not working... click the generated links...

function addLinks () {
for (var i=0, link; i<5; i++) {
            link = document.createElement("a");
            link.innerHTML = "Link " + i;
            link.onclick = function () {
                    alert(i);
            };
            document.body.appendChild(link);
    }
    }

But the following codes snippet works as our expectation.

function addLinks () {
for (var i=0, link; i<5; i++) {
        link = document.createElement("a");
        link.innerHTML = "Link " + i;
        link.onclick = function (num) {
                return function () {
                        alert(num);
                };
        }(i);
        document.body.appendChild(link);
}
}

i did try & find out the solution but i am not able to identified the solution between those two...

can any oue guide me how this works????

thanks in advanced

Edited by peter_budo: Somebody needs to learn difference between Java and JavaScript. Post moved

5
Contributors
5
Replies
7
Views
5 Years
Discussion Span
Last Post by Taywin
1

The variable i in your first script is out of scope. As a result, the function attached to the onclick does not correctly access to the variable value. The second one is a closure and is properly use. You need to read more on variable scope and closure...

Votes + Comments
yes
0
    function addLinks () {
        for (var i=0, link; i<5; i++) {
                link = document.createElement("a");
                link.innerHTML = "Link " + i;
                link.onclick = Function( "alert("+i+")" );

                document.body.appendChild(link);
        }
        }
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.