如何将功能动态添加到复选框

时间:2020-08-04 06:34:50

标签: javascript

我有一个简单的js代码,但是它不起作用(选中复选框时不会发出警报),什么是问题? :

function dynamicCheckbox() {          
        var checkbox = document.createElement('input');
        checkbox.type = "checkbox";
        checkbox.name = "chkbox";
        checkbox.id = "chkid" ;
        checkbox.style = "width:50px";
        checkbox.onclick = "openFiles()";            
}

function openFiles() {
    alert("hey");
}

2 个答案:

答案 0 :(得分:2)

仅分配函数本身,而不是字符串:

checkbox.onclick = openFiles;

完整示例:

function dynamicCheckbox() {          
        var checkbox = document.createElement('input');
        checkbox.type = "checkbox";
        checkbox.name = "chkbox";
        checkbox.id = "chkid" ;
        checkbox.style = "width:50px";
        checkbox.onclick = openFiles;
        
        document.body.appendChild(checkbox);
}

function openFiles() {
    alert("hey");
}

dynamicCheckbox();

答案 1 :(得分:2)

您可以将事件句柄添加为动态控件,如下所示:

document.addEventListener('click',function(e){
       if(e.target && e.target.id== 'chkid'){
            openFiles();
       }
});

function dynamicCheckbox() {          
        var checkbox = document.createElement('input');
        checkbox.type = "checkbox";
        checkbox.name = "chkbox";
        checkbox.id = "chkid" ;
        checkbox.style = "width:50px";
        //checkbox.onclick = "openFiles()";
        document.addEventListener('click',function(e){
          if(e.target && e.target.id== 'chkid'){
            openFiles();
         }
        });
        
        document.body.appendChild(checkbox);
 
}

function openFiles() {
    alert("hey");
}

dynamicCheckbox();