The problem is that:
Code:
links[i].onclick = function(){window.open(href,title); return false;};
Refers back to:
Code:
var links = webSites.getElementsByTagName("a");
var i, href, title;
So, whatever it's value, is what it will be. During the execution of the loop it's value is each of the link's hrefs in turn. But once the loop is finished, it's value is:
http://www.bbc.co.uk/
So whenever any of the onclick functions executes, that's the value for the variable href.
Here's what I would do. Well not exactly, I would change things a lot. But if I were only to to change what needs to be changed to get the existing code working I would:
Code:
window.onload=setupLinks;
function setupLinks()
{
var webSites = document.getElementById("divWebsites");
if (webSites)
{
//assign window.open event to divWebsites links
var links = webSites.getElementsByTagName("a"), i;
for (i=0; i<links.length; i++)
{
(function(i){
var href = links[i].getAttribute("href");
var title = links[i].getAttribute("title");
links[i].onclick = function(){window.open(href,title); return false;};
})(i);
}
}
}
In that way a self executing anonymous function is run for each link, assigning a unique onclick function with unique href and title variables.
But self executing anonymous functions are a little advanced and sometimes it's hard to grasp what's happening. This version which accomplishes the same thing might be clearer:
Code:
window.onload=setupLinks;
function setupLinks()
{
var webSites = document.getElementById("divWebsites");
if (webSites)
{
function assignCilcks(link){
var href = link.getAttribute("href");
var title = link.getAttribute("title");
link.onclick = function(){window.open(href,title); return false;};
}
//assign window.open event to divWebsites links
var links = webSites.getElementsByTagName("a"), i;
for (i=0; i<links.length; i++)
{
assignCilcks(links[i]);
}
}
}
There's a simpler way though if you take advantage of the meaning of the keyword this in the scope of an event assigned in this manner:
Code:
window.onload=setupLinks;
function setupLinks()
{
var webSites = document.getElementById("divWebsites");
if (webSites)
{
//assign window.open event to divWebsites links
var links = webSites.getElementsByTagName("a"), i;
for (i=0; i<links.length; i++)
{
links[i].onclick = function(){window.open(this.href,this.title); return false;};
}
}
}
Still not how I would do it, but we're getting closer. But I'll leave it at that because I think I've answered the question.
Bookmarks