我在JavaScript中构建一个UI,其中包括添加一列checkBoxes:
for (var key in ProcessAndPortList.list)
{
if (ProcessAndPortList.list.hasOwnProperty(key))
{
var dataRow = myTable.insertRow(-1);
var dataCell = dataRow.insertCell(-1);
dataCell.textContent = key;
dataCell = dataRow.insertCell(-1);
dataCell.textContent = ProcessAndPortList.list[key].port;
var terminationCheckbox = document.createElement('input');
terminationCheckbox.type = "checkbox";
terminationCheckbox.id = key;
terminationCheckbox.checked = ProcessAndPortList.list[key].markedForTermination;
terminationCheckbox.onchange = function() {
var isChecked = terminationCheckbox.checked;
markForTermination(key, isChecked);
};
var terminateCell = dataRow.insertCell(-1);
terminateCell.appendChild(terminationCheckbox);
}
}
问题在于,当检查每个条目的复选框时,将正确的ID与回调相关联。我似乎无法将那个复选框的ID添加到该函数中。我只得到最后一个checkBox的ID。如何获得正确的ID?
答案 0 :(得分:2)
更改此功能应该有效:
terminationCheckbox.onchange = function() {
markForTermination(this.id, this.checked);
};
答案 1 :(得分:0)
似乎您使用该闭包捕获变量键。但是for循环的每次迭代都有关键的变化。捕获一些在循环内声明的变量。
for (var key in ProcessAndPortList.list)
{
if (ProcessAndPortList.list.hasOwnProperty(key))
{
var local_scope_key = key
var dataRow = myTable.insertRow(-1);
var dataCell = dataRow.insertCell(-1);
dataCell.textContent = key;
dataCell = dataRow.insertCell(-1);
dataCell.textContent = ProcessAndPortList.list[key].port;
var terminationCheckbox = document.createElement('input');
terminationCheckbox.type = "checkbox";
terminationCheckbox.id = key;
terminationCheckbox.checked = ProcessAndPortList.list[key].markedForTermination;
terminationCheckbox.onchange = function() {
var isChecked = terminationCheckbox.checked;
markForTermination(local_scope_key, isChecked);
};
var terminateCell = dataRow.insertCell(-1);
terminateCell.appendChild(terminationCheckbox);
}
}