I have a web site that gets links generated dynamically. I would like to see if I can add an onclick event handler to track external links. I am looking to see links that has target=”new” ( which means external to our site) and add the event handler
html code
<a target="new" href="http://twitter.com/cnn">CNN</a>
The code I tried to test is not working. Let me know what is wrong in my code or should I some home append the onclick event to the external links?
Js code
var links = document.getElementsByTagName("a");
for (var i=0; <links.length; i++) {
if(links[i].target == 'new'){
links[i].onclick = function() {
alert("Added onClick: " + links[i].href);
}
}
}
Another answer here is what you should go with (using this) but it’s worth addressing the issue of closures in for loops.
If you want to use a variable that changes for each iteration in a for loop in a closure that’s created in that for loop, define and call an anonymous function that returns a function to be bound (binded?) to the onclick event.
Since the parameter (obj) to the anonymous function is passed by value it won’t change in subsequent iterations for the for loop. The returned function will have its own copy of the object.
A lot of stuff in Javascript starts making sense when you think of functions as objects that can be passed around.