我有一个用于创建表行的javascript代码:
function create_row() {
var table = document.getElementById("main_table");
var n = table.rows.length;
var m = table.rows[0].cells.length;
var row = table.insertRow(n);
for (i=2; i<m; i++) {
var cell = row.insertCell(i);
cell.innerHTML = "<input size=4>";
cell.addEventListener("change", function () {
console.log("Column of a cell: " + cell.cellIndex);
})
}
}
document.getElementById('create_row').onclick = create_row;
我的目的是,当用户在单元格中键入某些内容时,我想打印该值。但是,cellIndex
始终是我的表中的列数(或m
)(据我了解,因为在创建所有单元格后单击该单元格,因此i
达到m
)。
当单元格的内容发生更改时,如何接收单元格的行、列和值?
哦
,Javascript闭包。试试这个:
function create_row() {
var table = document.getElementById("main_table");
var n = table.rows.length;
var m = table.rows[0].cells.length;
var row = table.insertRow(n);
for (i=2; i<m; i++) {
create_cell(i);
}
}
function create_cell(){
var cell = row.insertCell(i);
cell.innerHTML = "<input size=4>";
cell.addEventListener("change", function () {
console.log("Column of a cell: " + cell.cellIndex);
})
}
document.getElementById('create_row').onclick = create_row;