在javascript中选中复选框时创建复选框

问题描述

|
    var container = document.getElementById(\'container\'),template = \'<li>\\
        <input type=\"checkBox\">\\
    </li>\\
    <li>\\
        <input type=\"checkBox\">\\
    </li>\\
    <li>\\
        <input type=\"checkBox\">\\
    </li>\';

container.onchange = function(e) {
    var event = e || window.event,target = event.srcElement || event.target;

    if( target.checked && target.parentNode.getElementsByTagName(\'ul\').length === 0 ) {
        var ul = document.createElement(\'ul\');
        ul.innerHTML = template;
        target.parentNode.appendChild(ul);
    }
};
HTML:
    <ul id=\"container\">
    <li>
        <input type=\"checkBox\">
    </li>
    <li>
        <input type=\"checkBox\">
    </li>
    <li>
        <input type=\"checkBox\">
    </li>
</ul>
我创建了三个复选框。选中一个复选框后,另一个三框将出现在其下,依此类推。现在的问题是如何为每个复选框分配唯一的ID和onclick事件     

解决方法

首先,我将使用jQuery(或其他框架)来做到这一点。在此示例中,我使用jQuery。 然后,要在文档中创建一个元素,请执行以下操作:
function addCheckboxes(){
    /* this will create the box but will not place it into your document */
    var newCheckboxes = $(\'<input type=\"checkbox\" /><input type=\"checkbox\" /><input type=\"checkbox\" />\');

    /* this will put the code in the docuement */
    $(\'#container\').append(newCheckboxes);
}
然后要附加事件,请使用jQuery .live()函数:
    /* this will attach the click event */
    $(\'#container input\').live(\'click\',function(){
        addCheckboxes();
    });
请注意,这会将相同的事件分配给所有复选框。 如果要将不同的事件附加到每个复选框,则应找到一种方法来迭代addCheckboxes函数内的每个复选框,或者分别创建每个复选框,并在每次创建事件时附加该事件。 如果您想在线运行代码并与我们共享,请随时在此网站上创建jsFiddle。     ,已经完成了添加行和为每行动态生成ID以及附加脚本以添加和删除行的功能。 检查此链接