【问题标题】:Clone div and remove class without changing the original one克隆 div 并删除类而不更改原始类
【发布时间】:2017-10-25 16:38:53
【问题描述】:

我想使用 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 中。

【问题讨论】:

  • 我没有看到删除类的代码,你能用删除类更新你的代码吗,你在哪里尝试删除类
  • next.children(':first-child').removeClass('col-sm-offset-1').clone().appendTo($(this)); //这里我删除了克隆的 div 类

标签: javascript jquery twitter-bootstrap bootstrap-modal


【解决方案1】:

你可以像这样在clone之后使用removeClassaddClass

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

【讨论】:

    【解决方案2】:

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

    $('.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));                
            }
    
        });
    

    将“your-element-identity-class”替换为您要删除的类名。 原始参考。来自-How to remove the selected element during a clone() operation

    【讨论】:

      【解决方案3】:

      您应该能够在附加对象之前对其运行removeClass(),无论您要将其附加到何处。

      【讨论】:

      • next.children(':first-child').removeClass('col-sm-offset-1')‌​.clone().appendTo($(‌​this));我使用它,但它也从原始 div 中删除
      猜你喜欢
      • 1970-01-01
      • 2016-02-21
      • 2012-12-02
      • 1970-01-01
      • 2013-03-27
      • 1970-01-01
      • 1970-01-01
      • 2012-01-11
      • 2013-09-15
      相关资源
      最近更新 更多