javascript jquery删除重复的li

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3838845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 02:24:39  来源:igfitidea点击:

jquery remove duplicate li

javascriptjqueryhtml

提问by dave

<ul id="myid">   
<li>microsoft</li>  
<li>microsoft</li>  
<li>apple</li>  
<li>apple</li>  
</ul>   

I want to remove duplicates from liby using jquery.

我想li使用 jquery从中删除重复项。

How can I do that?

我怎样才能做到这一点?

采纳答案by andres descalzo

exampleI find that the script is faster

例如我发现脚本更快

var liText = '', liList = $('#myid li'), listForRemove = [];

$(liList).each(function () {

  var text = $(this).text();

  if (liText.indexOf('|'+ text + '|') == -1)
    liText += '|'+ text + '|';
  else
    listForRemove.push($(this));

})?;

$(listForRemove).each(function () { $(this).remove(); });

回答by Tomalak

uniqueLi = {};

$("#myid li").each(function () {
  var thisVal = $(this).text();

  if ( !(thisVal in uniqueLi) ) {
    uniqueLi[thisVal] = "";
  } else {
    $(this).remove();
  }
})

This build an index (an object) of unique values. For your example, uniqueLiwill look like this afterwards:

这会构建一个唯一值的索引(一个对象)。对于您的示例,之后uniqueLi将如下所示:

{
  "microsoft": "", 
  "apple": ""
}

So whenever a value is encountered that has been added to the index before, the associated <li>gets removed.

因此,每当遇到之前已添加到索引中的值时,相关联的值<li>就会被删除。

回答by Thariama

You could use

你可以用

var inner = [];
$('li').each( function(index, Element){
    if (jQuery.inArray(this.innerHTML, inner) == -1){
      inner.push(this.innerHTML);
    }
    else {
      $(this).remove();
    }
});

回答by Mark Bell

Here's a function that will do it, a slightly different way:

这是一个可以执行此操作的函数,方式略有不同:

function removeDuplicateItems(id) {
    var ul = $('#' + id);

    $('li', ul).each(function() {
        if($('li:contains("' + $(this).text() + '")', ul).length > 1)
            $(this).remove();
    });
}

Call with removeDuplicateItems('myid');

removeDuplicateItems('myid');

回答by jaysponsored

I have used @Thariama solution in the past, but I have compatibility problems with IE6 (I still needs to support this dinosaur).

以前用过@Thariama 的解决方案,但是IE6有兼容性问题(我还是需要支持这个恐龙)。

If the item repeats, so remove it from ul. It works with dynamic added li.

如果该项目重复,则将其从 ul 中删除。它适用于动态添加的 li。

            var seen = {};
            $("ul#emails_exclusion_list").find("li").each(function(index, html_obj) {
                txt = $(this).text().toLowerCase();

                if(seen[txt]) {
                    $(this).remove();
                } else {
                    seen[txt] = true;
                }
            });