E
Eleandor
Well, I realise it's not so much a bug as it is a feature.
I've written a quick testpage:
<html>
<head>
<script type="text/javascript">
Person = (function() {
return function() {
var self = this;
this.messages = function() {
for(var i = 0; i < 10; i++) {
var elm = document.createElement("div");
elm.innerHTML = "Display " + i;
elm.onclick = function() {
self.shout(i);
};
document.body.appendChild(elm);
}
};
this.shout = function(number) {
alert(number);
};
};
}());
function LoadPage() {
var p = new Person();
p.messages();
}
</script>
</head>
<body onload="LoadPage()">
</body>
</html>
The html page shows "Display x" with x a number from 0 to 9. However,
as I click it, it displays 10 regardless of which element I clicked. I
can understand why, since the value of i is 10 when the loop ends. But
what I'm trying to achieve is to create a function that uses the
actual value of i, at the moment when the onclick function is created.
So "Display 5" should actually display 5, using the literal value of i
when the function is created, instead of the value of i at the time of
execution.
How can I achieve something like this?
Thanks,
- Bart
I've written a quick testpage:
<html>
<head>
<script type="text/javascript">
Person = (function() {
return function() {
var self = this;
this.messages = function() {
for(var i = 0; i < 10; i++) {
var elm = document.createElement("div");
elm.innerHTML = "Display " + i;
elm.onclick = function() {
self.shout(i);
};
document.body.appendChild(elm);
}
};
this.shout = function(number) {
alert(number);
};
};
}());
function LoadPage() {
var p = new Person();
p.messages();
}
</script>
</head>
<body onload="LoadPage()">
</body>
</html>
The html page shows "Display x" with x a number from 0 to 9. However,
as I click it, it displays 10 regardless of which element I clicked. I
can understand why, since the value of i is 10 when the loop ends. But
what I'm trying to achieve is to create a function that uses the
actual value of i, at the moment when the onclick function is created.
So "Display 5" should actually display 5, using the literal value of i
when the function is created, instead of the value of i at the time of
execution.
How can I achieve something like this?
Thanks,
- Bart