如何删除元素与重复类后无限滚动追加

How to remove elements with duplicate class after infinite scroll append

本文关键字:无限 追加 滚动 何删除 删除 元素      更新时间:2023-09-26

我正在用jQuery实现一个基于AJAX的无限滚动函数。当无限滚动追加到DOM时,一些新的div可能是重复的,因为其他用户在同一页面上添加其他评论可能会打乱mysql的顺序。

因此,我需要删除由于无限滚动追加而添加到页面的任何重复注释。

格式为

 <div class = "comment 1">comment text</div>

所以任何重复项都是

 <div class = "comment 12">comment text</div>
 <div class = "comment 12">comment text</div>
从本质上讲,我所寻找的是一种循环遍历类中所有带有"comment"的div的方法,并删除任何出现多次注释编号的div,例如上面示例中的"comment 12",同时保留至少一个副本。

我如何做到这一点?

它不是很漂亮,但是像这样的东西?

$('.comment').each(function() {
    var currentclass = $.trim($(this).attr('class').replace('comment', ''));
    if ($('.comment.' + currentclass).length > 1) {
        $(this).remove();
    }
});

这里有一个小提琴:http://jsfiddle.net/Niffler/5w33E/

您可以尝试按类遍历注释,并删除已列出的注释的类:

  var matches = [];
  $("div[class^='comment']").each(function () {
    var thisClass = this.className;
    if (matches.indexOf(thisClass) > -1) {
      $(this).remove();
    } else {
      matches.push(thisClass);
    }
  });

"^="操作符匹配任何以"comment"开头的类。