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

JavaScript is not Java, I think you would get more suiting replies in this forum.

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...

commented: yes +14

were you ever able to solve this?

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

Here is a good read on closure.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.