动态复选框创建以在单击时运行函数

dynamic checkbox creation to run function onclick

本文关键字:运行 函数 单击 复选框 创建 动态      更新时间:2023-09-26

我有一个函数,用于为数组中的每个项目创建一个复选框。

我遇到的问题是,当单击它时尝试创建一个函数时,这个函数也需要从数组中的项目动态创建,但似乎只得到第一项。

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'。

将 onclick 函数修改为

checkbox.onclick = (function(dataType) {
    return function () {
        console.log(dataType);
    };
}(dataTypeId1))

继续阅读 Javascript 闭包以了解更多信息