【问题标题】:Best way to display only distinct value from multiple div tags with same class name仅显示来自具有相同类名的多个 div 标签的不同值的最佳方法
【发布时间】:2013-09-12 04:13:36
【问题描述】:

如何仅显示具有相同类名的多个 div 标签中的 distinct 值

<div class="categories">cat 1</div>
<div class="categories">cat 1</div>
<div class="categories">cat 2</div>
<div class="categories">cat 2</div>
<div class="categories">cat 2</div>
<div class="categories">cat 3</div>
<div class="categories">cat 3</div>

我想只显示不同的值并隐藏其余的值

  • 猫 1
  • 猫 2
  • 猫 3

【问题讨论】:

标签: javascript jquery html jquery-selectors


【解决方案1】:

大概是这样的吧?

  $('.categories').filter(function(){ //use filter on all .categories
       var txt = $.trim(this.innerHTML); //Get the text of current
       return ($(this).nextAll().filter(function () { //filter all of the proceeding siblings which has the same text
            return $.trim(this.innerHTML) === txt
        }).length); //send true or false (in fact truthy or falsy to ask to hide the current element in question)
   }).hide(); 

Fiddle

另一个衍生品,这将隐藏第一个衍生品,而前一个衍生品将隐藏最后一个。

$(function () {
    $('.categories').each(function(){
       var txt = $.trim(this.innerHTML);
       $(this).nextAll(':visible').filter(function () {
            return $.trim(this.innerHTML) === txt
        }).hide();
    });
});

Fiddle

另一种方法,它需要更少的迭代并创建一个选择器,其中包含要隐藏的元素的索引。

$(function () {
    var arrText = [];
    $(($('.categories').map(function(){
       var txt = $.trim(this.innerHTML);
        if(arrText.indexOf(txt) == -1) 
            arrText.push(txt);
        else 
           return('.categories:eq(' + $('.categories').index(this) + ')'); //create the selector with eq
    }).get().join(','))).hide();
});

Fiddle

【讨论】:

  • 如果还有其他的div标签。你如何忽略它们?
    猫 1
    猫 1
    foo 1
    猫 2
    foo 2
    猫 2
    猫 2
    猫 3
    猫 3
  • @user2769820 尝试在我的回答中提供的小提琴中替换您的 html,看看是否有任何问题。
【解决方案2】:

你可以用这个:

$(function () {
    var text = []
    $('.categories').each(function () {
        if ($.inArray($(this).text(), text)<0) {
            text.push($(this).text())
        }
    });
    // you can use now the variable "text"
    console.log(text);
});

演示here

【讨论】:

  • 似乎是这里最好的解决方案。
【解决方案3】:
$('.categories').each(function() {
    var textContent = $(this).text();
    if ($('.categories:visible').not(this).filter(function() {
        return $(this).text() == textContent;
    }).length) {
        $(this).hide();
    }
});

小提琴:http://jsfiddle.net/cYjyn/1/

编辑:更改 :contains 支持 .filter 以避免子匹配

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-19
    相关资源
    最近更新 更多