0

I am trying to use a for loop to generate onclick functions for each of my 4 links below. Right now it doesn't work at all and I am unsure why?

Fiddle: http://jsfiddle.net/7WYfF/

<p><a href="#" id="link0">Link0</a></p>
<p><a href="#" id="link1">Link1</a></p>
<p><a href="#" id="link2">Link2</a></p>
<p><a href="#" id="link3">Link3</a></p>

<script>
for (var i = 0; i < 3; i++) {
    var temp = "link" + i;

    [temp].onclick = function () { 
        alert("You just clicked link: " + i);
    };
}
</script>
user1822824
  • 2,478
  • 6
  • 41
  • 65

3 Answers3

3

Two things. First you need to wrap i in a closure to store the value that you want. Second [temp] will not select a DOM element, you will need to do that differently.

for (var i = 0; i < 3; i++) {
    var temp = "link" + i;

    document.getElementById(temp).onclick = (function(t) {
        return function (e) { 
            alert("You just clicked link: " + t);
        };
    })(i);
}
fuzic
  • 2,492
  • 16
  • 22
0

Try this...

var temp = document.getElementById("link" + i);

temp.onclick = function...

Bafsky
  • 761
  • 1
  • 7
  • 16
0

you should use getElementById :

document.getElementById("link" + i);

also i suggest you use jQuery framework. it's so easy than bare javascript.

Amir Molaa
  • 1,103
  • 1
  • 9
  • 9