I'm trying to make this anchor
element change its text when you click on it, but it just won't work.
The element in question is part of a set of other anchors inside a table, according to the following structure:
- table
- row
- cell → anchor
- cell → anchor
- cell → anchor
- row
- cell → anchor
- cell → anchor
- cell → anchor
- row
- cell → anchor
- cell → anchor
- cell → anchor
- row
And it's populated by the following script:
var initButtonAction = function() {
var table = document.getElementById("Table");
var number = document.getElementById("Number");
var size = parseInt(number.value);
clearChildren(table); // A function I improvised to clear an element's contents
for (var i = 0; i < size; i++) {
var row = document.createElement("tr");
for (var j = 0; j < size; j++) {
var cell = document.createElement("td");
var anchor = document.createElement("a");
var text = document.createTextNode("O");
anchor.id = "Id_"+i+"_"+j;
anchor.addEventListener("click", function(e) {
var newValue = document.createTextNode(parseInt(Math.random()*10)+1);
clearChildren(anchor);
anchor.appendChild(newValue);
e.preventDefault();
}, false);
anchor.appendChild(text);
cell.appendChild(anchor);
row.appendChild(cell);
}
table.appendChild(row);
}
}
The problem is that when I click on any anchor, only the last one gets changed, for example:
O O O O O
O O O O O
O O O O O
O O O O O
O O O O O
Changes to this:
O O O O O
O O O O O
O O O O O
O O O O O
O O O O 8
No matter what "O" I press.
However, I did the same on another project (using the same symbol in the event listener function) and it worked pretty fine, the code is as follows:
var row = document.createElement('tr');
// Create and initialize other elements
row.id = 'Product'+globalProductsIdCounter+'Row';
// Some more irrelevant processing
opcAnchor.id = 'Product'+globalProductsIdCounter+'OpcAnchor';
opcAnchor.href = '#';
opcAnchor.addEventListener('click', function() {
ProductsTableBody.removeChild(row);
}, false
);
opcAnchor.appendChild(document.createTextNode('(eliminar)'));
Why does the first example doesn't work?