E
Emre Sevinc
Take a look at the following snippet:
<html>
<head>
<script>
function add(elementId) {
var container = document.getElementById(elementId);
for (var i = 0; i < 10; i++) {
var elt = document.createElement('div');
elt.innerHTML = "" + i;
// Beware!
elt.onclick = function () {window.alert("" + i);};
container.appendChild(elt);
}
}
</script>
</head>
<body>
<div id=myDiv onClick=add('myDiv')>
Here's my DIV
</div>
</body>
</html>
Now, when you click on the DIV element it produces and adds 10
DIV elements. That's okay but when you click on the child DIVs,
alert gives you 10. Not that you click on the first one and
you get 0 and the next one and 1, etc.
Why does that anonymous function always show the value of 10?
I'm very surprised at this output!
Any ideas, explanations, tips?
--
Emre Sevinc
eMBA Software Developer Actively engaged in:
http:www.bilgi.edu.tr http://ileriseviye.org
http://www.bilgi.edu.tr http://fazlamesai.net
Cognitive Science Student http://cazci.com
http://www.cogsci.boun.edu.tr
<html>
<head>
<script>
function add(elementId) {
var container = document.getElementById(elementId);
for (var i = 0; i < 10; i++) {
var elt = document.createElement('div');
elt.innerHTML = "" + i;
// Beware!
elt.onclick = function () {window.alert("" + i);};
container.appendChild(elt);
}
}
</script>
</head>
<body>
<div id=myDiv onClick=add('myDiv')>
Here's my DIV
</div>
</body>
</html>
Now, when you click on the DIV element it produces and adds 10
DIV elements. That's okay but when you click on the child DIVs,
alert gives you 10. Not that you click on the first one and
you get 0 and the next one and 1, etc.
Why does that anonymous function always show the value of 10?
I'm very surprised at this output!
Any ideas, explanations, tips?
--
Emre Sevinc
eMBA Software Developer Actively engaged in:
http:www.bilgi.edu.tr http://ileriseviye.org
http://www.bilgi.edu.tr http://fazlamesai.net
Cognitive Science Student http://cazci.com
http://www.cogsci.boun.edu.tr