天天看点

jQuery将DIV复制为另一个DIV 并且功能同在(delegate的用法)

jQuery将DIV复制为另一个DIV 并且功能同在(delegate的用法)
<div id="copied"> //此div为原先存在的div
    <div>
        <div class="table-H" style="">
            <input type="text" value=""><a href="javascript:void(0)" target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow"  class="table-look remove_column">删除栏目</a>
        </div>
        <div class="line"></div>
    </div>
</div>

<br>

<a href="javascript:void(0)" target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow"  class="table-look add_column">新增栏目</a>

<section style="display: none" id="template">  //此模块为 要复制的模板
    <div class="add_line">
        <div class="table-H">
            <input type="text" value=""><a href="javascript:void(0)" target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow"  class="table-look remove_column">删除栏目</a>
        </div>
        <div class="line"></div>
    </div>
</section>
           

让复制出来的div 删除功能同在   需要用绑定事件  但是试过on  bind 都不可以  最后发现delegate可以  

此处之所以不用克隆(clone) 是因为 在你复制出来一个后  再次点击的时候 会出现多个 所以最后使用了 append()

/**
 * 删除栏目
 */
$('#copied').delegate(".remove_column", "click", function () {
    $(this).parent().parent().remove();
});

/**
 * 新增栏目
 */
$('.add_column').click(function () {
    $('#copied').append($('#template').html());

});