Hi,
I writing an app with Javascript in an OO style. Suppose I have a
class named Band with the following code:
function Band(str){
var chk;
var name = str;
this.attachTo=function(element){
element.innerHTML += " <input type='checkbox' id='"+name+"'>" + name
+ "<br/>";
chk = document.getElementById(name);
chk.onchange=function(){
alert("you've clicked on "+name+"!");
}
}
}
The attachTo method is responsible for appending some html code at a
DOM element passed as an argument. Note that the class has a field
called chk, which, in fact, refers to a checkbox. But it is only
initialized inside attachTo, after the html code is appended. So
chk.onchange is assigned a function that is supposed to alert a
message with the name field of the object whenever the user clicks on
that checkbox.
Now consider this test function:
function BandTest(){
var container = document.getElementById('container');
var bands = new Array(
new Band('Beatles'),
new Band('Supertramp'),
new Band('Pink Floyd')
);
for (var i = 0; i < bands.length; i++)
bands[i].attachTo(container);
}
The body element of the main page was assigned "BandTest()". So, as
expected, when the page loads, it prints the three names (each one
following a checkbox). Also, if I click on Pink Floyd's checkbox, I
receive the following alert: "you've clicked on Pink Floyd!". So far,
so good.
But if I click on Beatles or Supertramp's checkboxes, nothing happens.
It seems as if only one object was actually instantiated. But I have
explicitly instantiated three of them, and each one was assigned to a
position in the bands array. What is wrong?
Thanks in advance.