Skip to content

Instantly share code, notes, and snippets.

@cschep
Created March 24, 2015 21:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cschep/4181917ce4c78f457816 to your computer and use it in GitHub Desktop.
Save cschep/4181917ce4c78f457816 to your computer and use it in GitHub Desktop.
javascript closure example
<!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