S
Sean Dockery
I have the following HTML file that I've been using for testing...
<html>
<head>
<script type="text/javascript">
<!--
function handleWindowLoad() {
var items = [];
for (var i = 0; i < 11; i++) {
items = "item" + (i + 1);
}
var parent = document.getElementById("parent");
for (var i = 0; i < items.length - 1; i++) {
var child = document.createElement("div");
child.innerHTML = items;
var currentItem = items;
handler = new Object();
handler.currentItem = currentItem;
handler.onclick = function() {
handleButtonClick.call(handler);
}
child.attachEvent('onclick', handler.onclick);
parent.appendChild(child);
}
}
window.onload = handleWindowLoad;
function handleButtonClick() {
alert(this.currentItem);
}
//-->
</script>
</head>
<body>
<div id="parent">
</div>
</body>
</html>
What I want is for the handleButtonClick function to show an alert with the
text "item1", "item2", and so forth for each of the items clicked by the
user. Instead, it shows "item10" for every child of the parent element.
But I don't understand why. I thought that the code would be creating a
closure (am I using this term correctly?) for each child element, but it
apparently is not. Can anyone provide me with a solution that can clear up
my confusion?
I have also read that closures are bad from the point of view that they can
often be the cause of memory leaks. Is there a memory-leak-less way to
achieve the same thing that as the code above?
Thanks for your time.
<html>
<head>
<script type="text/javascript">
<!--
function handleWindowLoad() {
var items = [];
for (var i = 0; i < 11; i++) {
items = "item" + (i + 1);
}
var parent = document.getElementById("parent");
for (var i = 0; i < items.length - 1; i++) {
var child = document.createElement("div");
child.innerHTML = items;
var currentItem = items;
handler = new Object();
handler.currentItem = currentItem;
handler.onclick = function() {
handleButtonClick.call(handler);
}
child.attachEvent('onclick', handler.onclick);
parent.appendChild(child);
}
}
window.onload = handleWindowLoad;
function handleButtonClick() {
alert(this.currentItem);
}
//-->
</script>
</head>
<body>
<div id="parent">
</div>
</body>
</html>
What I want is for the handleButtonClick function to show an alert with the
text "item1", "item2", and so forth for each of the items clicked by the
user. Instead, it shows "item10" for every child of the parent element.
But I don't understand why. I thought that the code would be creating a
closure (am I using this term correctly?) for each child element, but it
apparently is not. Can anyone provide me with a solution that can clear up
my confusion?
I have also read that closures are bad from the point of view that they can
often be the cause of memory leaks. Is there a memory-leak-less way to
achieve the same thing that as the code above?
Thanks for your time.