role of (table.rows[i])
or why defined function when return call?
function onRowClick(tableId, callback) {
var table = document.getElementById(tableId),
rows = table.getElementsByTagName("tr"),
i;
for (i = 0; i < rows.length; i++) {
table.rows[i].onclick = function (row) {
return function () {
callback(row);
};
}(table.rows[i]);
}
};
the problem with `var`s is that their value is function-scoped. So if you just wrote for (var i = 0; i < rows.length; i++) { table.rows[i].onclick = () => callback(table.rows[i]); } and tried clicking any row, you'd find that it behaves as if you always clicked the last row. If you wrap the handler in a function and pass the row to it (or simply the index), the wrapper will contain the corrent value and if you click any row, the handler acts correctly. ...but if you use let instead of var, this code will work just as fine: for (let i = 0; i < rows.length; i++) { table.rows[i].onclick = () => callback(table.rows[i]); } and your snippet is just legacy you can now avoid
Обсуждают сегодня