2012-04-04 127 views
0

假设我有这样的识别重复的值与jQuery

<ul> 
<li>Item 1</li> 
<li>Item 2</li> 
<li>Item 3</li> 
<li>Item 1</li> 
</ul> 

列表使用jQuery我怎么能确定何时值重复。 我的意图是给重复值一个替代的风格。

回答

2

您可以遍历所有<li>对象,获取它们的文本并将其收集到您用作索引的对象中(以提高效率)。完成后,查看哪些项目具有超过一个给定文本的元素,并向它们添加特殊类。出于效率原因,此解决方案使用对象来构建索引。该代码是这样的:

HTML:

<ul id="list"> 
<li>Item 1</li> 
<li>Item 2</li> 
<li>Item 3</li> 
<li>Item 1</li> 
</ul>​ 

的Javascript评论:

(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"); 
     } 
    }); 
})();​ 

工作演示:http://jsfiddle.net/jfriend00/zDhjD/

+0

谢谢您的回答。还有一件事我需要调整。我只想“添加类”到dublicate的价值而不是原来的。目前该课程已添加到原版。 – jamjam 2012-04-04 15:06:58

+0

@jamjam - 我更新了代码和演示,不添加类到找到的第一个。 – jfriend00 2012-04-04 15:12:01

+0

完美。谢谢。 – jamjam 2012-04-04 15:14:18

0
$("ul li").each(function(){ 
    var val = $(this).text(); 
    $("ul li").not(this).each(function(){ 
    if($(this).text() == val){ 
    $(this).addClass("mystyle"); 
    } 
    }); 
}); 

http://jsfiddle.net/tscRG/

0

试试这个:

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

Demo上的jsfiddle