Created
March 24, 2015 21:24
-
-
Save cschep/4181917ce4c78f457816 to your computer and use it in GitHub Desktop.
javascript closure example
This file contains 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>a quick example</title> | |
<style type="text/css"> | |
button { | |
font-size: 22pt; | |
width: 100px; | |
height: 100px; | |
} | |
</style> | |
</head> | |
<body> | |
<button id="1">one</button> | |
<button id="2">two</button> | |
<button id="3">three</button> | |
<button id="4">four</button> | |
<button id="5">five</button> | |
<script> | |
/* | |
//doesn't work ! | |
for (var i = 1; i < 6; i++) { | |
document.getElementById(i).addEventListener('click', function() { | |
console.log(i); | |
}); | |
} | |
//works ! | |
for (var i = 1; i < 6; i++) { | |
document.getElementById(i).addEventListener('click', function(val) { | |
return function() { | |
console.log(val); | |
} | |
}(i)); | |
} | |
*/ | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment