如何在div中为动态创建的复选框调用唯一的函数 [英] How to call unique function for dynamically created checkboxes in a div
问题描述
function initAllButtons()变量,长度)
{
for(c = 0; c {
clicks.push(true);
}
for(i = 0; i {
var label = document.createElement );
var checkbox = document.createElement(input);
checkbox.type =checkbox;
checkbox.checked = true;
checkbox.value = btns [i];
checkbox.class =colorCoder;
label.appendChild(checkbox);
document.getElementById('Buttons')。appendChild(checkbox);
$('#Buttons')。on('click',function(){updateData(i,clicks);});
}
}
Btns只是一个字符串数组。我真的想调用UpdateData函数(我已经测试和工作原理应该)与按下的按钮的值或索引,但似乎没有什么工作。
这个版本只是使用index = 10来调用updateData 10次。显然不是把按钮看成单独的东西。我做错了什么?
问题是你在你的点击处理程序中什么都不做引用clicked元素。为此,您需要指定selector作为 on()
的参数。可能如下:
$('#Buttons')。on('click',':checkbox' (){
//确定被点击项目的索引
var index = $('#Buttons:checkbox')。index(this);
//调用你的函数
updateData (index,clicks);
}
你只需要执行一行代码一次。
I am trying to dynamically create a set of check-boxes that each call a function differently when clicked
function initAllButtons(variable, length)
{
for(c = 0; c < length; c++)
{
clicks.push(true);
}
for(i = 0; i < length; ++i)
{
var label = document.createElement("label");
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.checked = true;
checkbox.value = btns[i];
checkbox.class = "colorCoder";
label.appendChild(checkbox);
document.getElementById('Buttons').appendChild(checkbox);
$('#Buttons').on('click', function(){updateData(i,clicks);});
}
}
Btns is just an array of strings. I really want to call the UpdateData function (which I have tested and works like it should) with the value or index of the button pressed, but nothing seems to be working.
This version just calls updateData ten times with index = 10. It obviously is not looking at the buttons as individual things. What am I doing wrong?
The problem is that you are doing nothing in your click handler to reference the clicked element. To do that you need to specify selector as parameter to on()
. That might look like this:
$('#Buttons').on('click', ':checkbox', function() {
// determine index of clicked item
var index = $('#Buttons :checkbox').index(this);
// call your function
updateData(index,clicks);
}
You should also place this code after your loop as you only need to execute this line of code once.
这篇关于如何在div中为动态创建的复选框调用唯一的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!