Created
January 5, 2013 11:19
-
-
Save mplungjan/4461078 to your computer and use it in GitHub Desktop.
Loop with closure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<script> | |
// using bing since google does not like being inside a jsfiddle frame | |
var myLinks = [ | |
'http://bing.com/search?q=go', | |
'http://bing.com/search?q=visit', | |
'http://bing.com/search?q=explore', | |
'http://bing.com/search?q=funny%20pics' | |
]; // note no comma on the last item | |
window.onload=function() { | |
for (var i=0;i<myLinks.length;i++) { | |
// EITHER document.getElementById("d"+i).getElementsByTagName("a")[0]).href=myLinks[i]; | |
// OR | |
document.getElementById("d"+i).getElementsByTagName("a")[0].onclick=(function(idx) { | |
var idx = i; | |
return function() { // closure | |
location=myLinks[idx]; | |
return false; // cancel href | |
} | |
})(i); | |
} | |
} | |
</script> | |
</head> | |
<body> | |
<a href="http://jsfiddle.net/mplungjan/uGxkt/">DEMO</a> | |
<div id="d0"><a href="#">GO</a></div> | |
<div id="d1"><a href="#">VISIT</a></div> | |
<div id="d2"><a href="#">EXPLORE</a></div> | |
<div id="d3"><a href="#">FUNNY PICS</a></div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment