动态复选框创建以运行函数onclick

时间:2014-12-22 12:53:05

标签: javascript

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

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

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

1 个答案:

答案 0 :(得分:1)

将onclick功能修改为此

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

请阅读Javascript Closures了解更多

相关问题