我试图让这个 anchor
元素在您单击它时更改其文本,但它不起作用。
根据以下结构,相关元素是表内一组其他 anchor 的一部分:
- 表格
- 行
- 单元格 → anchor
- 单元格 → anchor
- 单元格 → anchor
- 行
- 单元格 → anchor
- 单元格 → anchor
- 单元格 → anchor
- 行
- 单元格 → anchor
- 单元格 → anchor
- 单元格 → anchor
- 行
它由以下脚本填充:
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);
}
}
问题是,当我点击任何 anchor 时,只有最后一个 anchor 发生变化,例如:
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
对此的更改:
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
无论我按什么“O”。
但是,我在另一个项目上做了同样的事情(在事件监听函数中使用相同的符号)并且效果很好,代码如下:
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)'));
为什么第一个示例不起作用?
最佳答案
只需对您的代码进行一点小小的更改即可。将 anchor.appendChild(newValue);
替换为 this.appendChild(newValue);
。请注意, anchor 变量将保存迭代后的最后一个元素。
anchor.addEventListener("click", function(e) {
var newValue = document.createTextNode(parseInt(Math.random()*10)+1);
clearChildren(anchor);
this.appendChild(newValue);
e.preventDefault();
}, false);
关于javascript - 使用 javascript 使元素改变它自己的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27181917/