动态复选框创建以在单击时运行函数
dynamic checkbox creation to run function 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'。
将 onclick 函数修改为
checkbox.onclick = (function(dataType) {
return function () {
console.log(dataType);
};
}(dataTypeId1))
继续阅读 Javascript 闭包以了解更多信息
相关文章:
- jQuery在元素的上下文中运行函数
- Promise函数在.then之后未运行函数化
- 在.append之后运行函数
- 在on.change事件之后运行函数
- 如果文本或值以字符开头,请运行函数
- 如何在节点模块中从命令行运行函数
- 在Fancybox中提交表单时运行函数
- Don'如果字段为空,则不运行函数
- Javascript:如何在页面重新加载后运行函数
- 成功ajax:如果是200状态代码,则运行函数else另一个函数
- 运行函数ifsuccess($.ajax)有200个状态代码
- JavaScript只有在最后一次被调用时才运行函数
- 在异步AJAX调用完成后,通过变量运行函数
- ng中继器打印结果0;当我运行函数时
- 谷歌扩展:如何在弹出窗口中按下按钮时在我的javascript文件中运行函数
- 获取对在 JavaScript 中运行函数的对象的引用
- 运行函数时出错
- 节点.js子进程中的运行函数
- $.getJSON 在返回数据后不会运行函数
- 如果onchange为true,如何运行函数