This is the code for one of my javascript classes:
function Foo(text)
{
var container = document.createElement('span');
container.innerHTML = text;
$("#fooContainer").append(container);
this.select = function()
{
$(container).addClass('selected');
}
this.getContainer = function()
{
return container;
}
this.getText = function()
{
return text;
}
}
At each page load I do the following:
var fooList = {};
fooList['foo1'] = new Foo('Foo 1');
fooList['foo2'] = new Foo('Foo 2');
fooList['foo3'] = new Foo('Foo 3');
This results in the spans for each foo
object being created correctly, resulting in this in the dom:
<div id="fooContainer">
<span>Foo 1</span>
<span>Foo 2</span>
<span>Foo 3</span>
</div>
However, if I do this:
fooList['foo1'].select();
Then it results in this:
<div id="fooContainer">
<span>Foo 1</span>
<span>Foo 2</span>
<span class="selected">Foo 3</span>
</div>
Rather than what's expected, which is this:
<div id="fooContainer">
<span class="selected">Foo 1</span>
<span>Foo 2</span>
<span>Foo 3</span>
</div>
It seems like the container
object of all foo
objects points to the container of the last foo, which in this case is foo 3. To test it out further I did this:
for (var key in fooList)
{
console.log(key);
console.log( fooList[key].getText() );
console.log(fooList[key].getContainer() );
}
This results in this being logged in firebug console (only showing it for the first foo):
foo1
Foo 1
<span>
When I click span, then in firebug, it points to the 3rd of the spans rather than the first or 2nd as expected.
Any ideas what I'm doing wrong? Do I need to set an id to the spans?