1

Code below is the code with my question.

var links=content.getElementsByTagName("a");

for(var i=0;i<links.length;++i)
{
    links[i].onclick=function()
    {
        document.getElementById("placeholder").setAttribute("src",this.href);
        return false;
    };
}

Here I try to add onclick functions to the links and I succeed in making this by using the code above. However, if I replace the this.href with links[i].href, the default event of switching page appears. I want to know the reason.

Booster
  • 1,650
  • 13
  • 18

1 Answers1

2

It'll happen because by the time you reach the onclick, links[i] will already have a different (possibly undefined) value. JS doesn't have block scope.

If you want, you could use Array.prototype.forEach, which takes a function, and therefore will keep scope.

Scimonster
  • 32,893
  • 9
  • 77
  • 89