克隆div并删除类而不更改原始类

时间:2017-05-25 06:15:55

标签: javascript jquery twitter-bootstrap bootstrap-modal

我想使用jQuery克隆div的内容,但是在我使用appendTo函数之前,我希望从原始类中删除该类。当我从克隆中删除该类时,它们也会从原始类中删除。

我的代码是:

$('.carousel .item').each(function(){
        var next = $(this).next();

        if (!next.length) {
            next = $(this).siblings(':first');
        }
        next.children(':first-child').clone().appendTo($(this));
        next.children(':first-child').addClass('col-sm-offset-1');

        for (var i=0;i<3;i++) {
            next=next.next();
            if (!next.length) {
                next = $(this).siblings(':first');
            }
            next.children(':first-child').clone().appendTo($(this));                 
        }

});

请注意,我不想从复制内容的实际div中删除类,我只想将其从复制的代码中删除,以便它不包含在克隆的div中。

3 个答案:

答案 0 :(得分:3)

您可以在removeClass之后使用addClassclone

 .clone().removeClass('oldClass').addClass('col-sm-offset-1')

答案 1 :(得分:1)

您可以先从克隆对象中删除元素,然后克隆到新对象,如下所示:

$('.carousel .item').each(function(){ var next = $(this).next();    
        if (!next.length) {
            next = $(this).siblings(':first');
        }
        var $block = next.children(':first-child');

        // Grab the and remove element class
        $block = $block.find('.your-element-identity-class').removeClass('your-element-identity-class');

        // Clone the block 
        var $clone = $block.clone();

        $clone.appendTo($(this));
        next.children(':first-child').addClass('col-sm-offset-1');

        for (var i=0;i<3;i++) {
            next=next.next();
            if (!next.length) {
                next = $(this).siblings(':first');
            }
            var $block = next.children(':first-child');

            // Grab the and remove element class
            $block = $block.find('.your-element-identity-class').removeClass('your-element-identity-class');

            // Clone the block 
            var $clone = $block.clone();

            $clone.appendTo($(this));                
        }

    });

替换&#34;你的元素身份类&#34;使用您要删除的班级名称。 原始参考。来自 - How to remove the selected element during a clone() operation

答案 2 :(得分:1)

您可以在追加对象之前运行removeClass(),无论您要将其追加到哪里。

相关问题