如何在动态创建的 iCheck 样式复选框上设置选中值

问题描述

我在 ajax 成功函数中动态填充复选框,如下所示:

//get the json response arrays
var coworker_result = response[0];
var shared_result = JSON.stringify(response[1]);

for (var i in coworker_result)
        {       
            var row = coworker_result[i];
            var coworkerID = row[0];
            var name = row[1];          
            
            //check if the checkBox should be checked or unchecked
            if (shared_result.indexOf(coworkerID) >= 0){
            console.log('found coworker '+coworkerID);
                
            //creating the checkBoxes
           $('#icheck-container').append(               
            '<p class="description text-white dd-report-text" ><span style="vertical-align:middle;"> 
            <input type ="checkBox" class="coworker-checkBox" id="'+coworkerID+'"> 
           </span>'+name+'</p>'
            )
            //this is where I attempt to set the checked value,but no love
             $("input#"+coworkerID).iCheck('check');
            }
            else{
            //do something else
            $('input#'+coworkerID+'').iCheck('uncheck');
            )
            
            }
            
        }
    //add iCheck class to the checkBoxes
    $('#icheck-container').iCheck({checkBoxClass: 'icheckBox_square-grey',radioClass: 'iradio_square- 
   grey'});

附加复选框工作正常,但附加像 $("#"+coworkerID).iCheck('check'); 这样的选中值是问题所在。我浏览了许多论坛和文档以找到解决方案,但没有任何结果。如果我给复选框一个静态 ID,它就可以正常工作,所以我猜这个挑战与复选框的动态 ID 相关。

解决方法

我这样做是为了复杂化。最终的解决方案是像这样在 for 循环中的输入元素中添加 'checked' 值:

$('#icheck-container').append(              
'<p class="description text-white dd-report-text" ><span style="vertical- 
align:middle;"><input type ="checkbox" class="coworker-checkbox" id="'+coworkerID+'  " 
checked></span>'+name+'</p>'
            )