取消选中复选框时,删除复制的元素

时间:2013-07-16 22:38:25

标签: jquery html

粘贴后的代码会在检查复选框时将<table>元素从一个<div>复制到另一个<div>。但是当复选框取消选中时,如何删除相同的元素。

  $(":checkbox").on('change', function () {

        if ($(this).hasClass('containerToCopy')) {

            if ($(this).is(':checked')) {
               $(this).closest('div').clone().appendTo("#divTestPrintContainer");

            } else {
              // if #divTestPrintContainer contains the element associated with the checkbox then remove it.                    
            }                
        }
    });

3 个答案:

答案 0 :(得分:2)

将数据参数添加到已设置为原始检查ID的复制元素,如果取消选中该复选框,则只需找到具有相应数据值的复制元素并将其删除。

类似的东西:

$(":checkbox").on('change', function () {

    if ($(this).hasClass('containerToCopy')) {

        if ($(this).is(':checked')) {
           var myClone = $(this).closest('div').clone();
           myClone.appendTo("#divTestPrintContainer");
           // Here I insert the 'data-id' attribute to the cloned element and assign
           // it the value of the id from the original element.  This is how we match
           // the cloned element with the original.
           myClone.attr('data-id', $(this).attr('id'));

        } else {
          // if #divTestPrintContainer contains the element associated with the checkbox then remove it.
          // Here we find a child element of the #divTestPrintContainer that contains
          // a 'data-id' attribute matching our checkbox id that is being unchecked.
          $('#divTestPrintContainer').find("[data-id='" + $(this).attr('id') + "']").remove();
        }                
    }
});

这假设你的原始元素包含识别每个元素的id。

答案 1 :(得分:1)

也许您应该尝试使用.not(':checked')

http://api.jquery.com/not/

答案 2 :(得分:-1)

$('#divTestPrintContainer').empty();

http://api.jquery.com/empty/