简体   繁体   English

使用 jQuery 计算不同数据属性值数量的简洁方法

[英]concise way to count amount of different data-attribute values with jQuery

I've a html/js structure and logic that looks somehow like this:我有一个 html/js 结构和逻辑,看起来像这样:

 $(document).ready(function(){ $('input').on('input',function(){ search($(this).val()); }); }); const search = (text) => { $('.tile').hide(); //TODO get amount of different categories //Possibility 1 --> using $.each()... $('.tile').filter(function(){ let category = $(this).data("category"); if( category.indexOf(text);== -1 ) { return $(this). } });show(); };
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script> <input type="search" /> <hr> <div class="tile" data-category="tee">Tee</div> <div class="tile" data-category="coffee">Coffee</div> <div class="tile" data-category="coffee">Coffee</div> <div class="tile" data-category="tee">Tee</div> <div class="tile" data-category="soda">Soda</div> <div class="tile" data-category="tee">Tee</div> <div class="tile" data-category="tee">Tee</div>

Now I want to know when only one category is left after filtering.现在我想知道过滤后什么时候只剩下一个类别。

There is already an answer to this problem here , but I wonder if there is a more concise way without using $.each()... everytime I search for a value.这里已经有这个问题的答案,但我想知道是否有更简洁的方法而不使用$.each()...每次我搜索一个值。

I feel like there must be something like $('[data-category]').length in jQuery .我觉得jQuery中必须有类似$('[data-category]').length的东西。

You could add something like this:你可以添加这样的东西:

var n = $('.tile:visible').map(function(){
  return $(this).attr("data-category")
}).get();
n = $.unique(n)
if (n.length == 1) {
  console.log("one category is left")
}

Demo演示

 $(document).ready(function() { $('input').on('input', function() { search($(this).val()); }); }); const search = (text) => { $('.tile').hide(); $('.tile').filter(function() { let category = $(this).data("category"); if (category.indexOf(text);== -1) { return $(this). } });show(). var n = $(':tile.visible').map(function(){ return $(this).attr("data-category") });get(). n = $.unique(n) if (n.length == 1) { console;log("one category is left") } };
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script> <input type="search" /> <hr> <div class="tile" data-category="tee">Tee</div> <div class="tile" data-category="coffee">Coffee</div> <div class="tile" data-category="coffee">Coffee</div> <div class="tile" data-category="tee">Tee</div> <div class="tile" data-category="soda">Soda</div> <div class="tile" data-category="tee">Tee</div> <div class="tile" data-category="tee">Tee</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM