使用jquery标识重复值

使用jquery标识重复值,jquery,list,html-lists,Jquery,List,Html Lists,假设我有一张这样的清单 <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 1</li> </ul> 项目1 项目2 项目3 项目1 使用jQuery如何识别值何时重复。 我的目的是为重复值提供一种替代样式。您可以循环浏览所有对象,获取它们的文本并将其收集到一个对象中,用作索引(以提高效率)。完成后

假设我有一张这样的清单

<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 1</li>
</ul>
  • 项目1
  • 项目2
  • 项目3
  • 项目1
使用jQuery如何识别值何时重复。
我的目的是为重复值提供一种替代样式。

您可以循环浏览所有
  • 对象,获取它们的文本并将其收集到一个对象中,用作索引(以提高效率)。完成后,查看哪些项具有多个元素和任何给定文本,并向其添加一个特殊类。出于效率考虑,此解决方案使用对象构建索引。代码的工作原理如下:

    HTML:

    ​工作演示:

    试试这个:

    ​$('ul > li')​.each(function(){
        var current = this;
        $('ul').find('li:contains(' + $(this).html() + ')').each(function(){
            if(current != this) {
                $(this).css('color', 'red');
            }
        });
    });​
    

    在jsFiddle上

    谢谢你的回答。还有一件事我需要调整。我只想将“addClass”添加到dublicate值,而不是原始值。目前,该类也被添加到了原始类中。@jamjam-I更新了代码和演示,使其不会将该类添加到找到的第一个类中。
    (function() {
        var index = {};
        $("#list li").each(function() {
            var text = $(this).text();
            // if this text not in the index yet, create an array for it
            if (!(text in index)) {
                index[text] = [];
            }
            // add this item to the array
            index[text].push(this);
        });
        // cycle through the index and find each item that has more than one DOM element
        $.each(index, function() {
            // "this" will be an array of DOM nodes
            if (this.length > 1) {
                $(this.slice(1)).addClass("duplicates");
            }
        });
    })();​
    
    $("ul li").each(function(){
       var val = $(this).text();  
       $("ul li").not(this).each(function(){
        if($(this).text() == val){
         $(this).addClass("mystyle");
        }
       });
    });
    
    ​$('ul > li')​.each(function(){
        var current = this;
        $('ul').find('li:contains(' + $(this).html() + ')').each(function(){
            if(current != this) {
                $(this).css('color', 'red');
            }
        });
    });​