0

假设我有一个这样的列表

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

使用 jQuery 如何识别值何时重复。我的目的是为重复值赋予另一种风格。

4

3 回答 3

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/

于 2012-04-04T14:35:57.277 回答
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/

于 2012-04-04T14:36:35.950 回答
0

试试这个:

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

jsFiddle 上的演示

于 2012-04-04T14:36:43.593 回答