jQuery删除带有类名的重复div

时间:2012-12-09 19:59:00

标签: jquery

所以基本上我的div就是这样产生的:

<div class="test className">content</div>
<div class="test className">content</div>
<div class="test className">content</div>
..
<div class="test className">content</div>

我正在尝试删除重复的div并仅保留最后一个!任何快速的想法?谢谢!

3 个答案:

答案 0 :(得分:11)

基于您提供的标记的快速创意

var $div = $('div.test.className:contains(content)');

if ($div.length > 1) {
   $div.not(':last').remove()
}

但我会在第一时间防止重复。

修改:以下是使用filterslice方法的另一种方法:

$('.test.className').filter(function() {
    return this.textContent === 'content';
}).slice(0, -1).remove();

在上面的代码片段中,使用-1作为.slice方法的第二个参数,集合中的最后一个元素将被忽略。

答案 1 :(得分:6)

类似的东西:

​$('.className').not(':last')​.remove();​​​​​​​​​​​​​

选择所有带.className的div,从选区中删除最后一个div,删除div的集合,然后保留最后一个。

演示:http://jsfiddle.net/j5728/

答案 2 :(得分:1)

ORIGINAL(请参阅下面的编辑)

正如Jan Dvorak所述,我不确定您认为哪些属性确定某个元素是另一个元素的副本,但是,以下内容并非特别快速但是更通用的解决方案:

(function($) {
  $.fn.removeDuplicates = function() {
    var original = [];

    this.each(function() {
      var el = this, $el, isDuplicate;

      $.each(original, function() {
        $el = $(el);

        // check whichever properties 
        // you believe determine whether 
        // it's a duplicate or not
        if (el.tagName === this.tagName && 
            el.className === this.className && 
            el.id === this.id && 
            el.value === this.value && 
            el.href === this.href && 
            $el.html() === $(this).html()) {
          isDuplicate = true;
          $el.remove();
        }
      });

      if (!isDuplicate) {
        original.push(el);
      }
    });
  };
}(jQuery));

您可以这样使用它:

$('.test').removeDuplicates();

// .. or even
$('div').removeDuplicates();

// .. or even
$('.test.className').removeDuplicates();

上述所有内容应按预期工作,如demonstrated here

修改

自从我写这篇文章已经过去几年了,我已经了解了Node.isEqualNode。它提供了一种更清晰的方式来执行此操作,因此更新的插件将如下所示(并将原始元素返回到链):

(function($) {
  'use strict';

  $.fn.removeDuplicates = function() {
    var $original = $([]);

    this.each(function(i, el) {
      var $el = $(el),
          isDuplicate;

      $original.each(function(i, orig) {
        if (el.isEqualNode(orig)) {
          isDuplicate = true;
          $el.remove();
        }
      });

      if (!isDuplicate) {
        $original = $original.add($el);
      }
    });

    return $original;
  };

}(jQuery));

一个工作示例是demonstrated here