0
我有一個函數用於爲數組中的每個項目創建一個複選框。動態複選框創建運行功能onclick
我遇到的問題是,當它試圖創建一個函數,當它被點擊時,這個函數也需要從數組中的項目動態創建,但似乎只能得到第一個項目。
function createCheckboxes(markerGroups) {
var container = document.getElementById('panel');
for (var i = 0; i < markerGroups.length; i++) {
var dataTypeId1 = markerGroups[i];
console.log(dataTypeId1);
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "chk" + markerGroups[i].dataTypeId;
checkbox.value = "value";
checkbox.id = "chk" + markerGroups[i].dataTypeId;
checkbox.onclick = function() {
console.log(dataTypeId1);
};
checkbox.checked = true;
var label = document.createElement('label')
label.htmlFor = "chk" + markerGroups[i].dataTypeId;
label.appendChild(document.createTextNode(markerGroups[i].dataTypeName));
container.appendChild(checkbox);
container.appendChild(label);
}
}
在上面的代碼中,我寫了2個日誌。第一次產生如預期的ID列表,例如,
1001
1002
1003
1004
1005
的onclick功能需要得到數組中的電流ID,但總是返回的第一個項目/ ID「1001」無論哪個複選框我點擊。
這工作不錯,但不知道如何...感謝您的鏈接信息,我將有一個讀。 – JBoom