我有以下 HTML 结构,这里类 post-4837
和 post-4836
重复。我必须只显示第一个并隐藏重复的:
<li class="product">
<div class="some-other-class-names post-4837">....</div>
</li>
<li class="product">
<div class="some-other-class-names post-4837">....</div>
</li>
<li class="product">
<div class="some-other-class-names post-4836">....</div>
</li>
<li class="product">
<div class="some-other-class-names post-4836">....</div>
</li>
<li class="product">
<div class="some-other-class-names post-4836">....</div>
</li>
如何使用 CSS 或 jQuery 隐藏重复的产品类?
实际上,我想隐藏所有 post-*
重复的 .product
类。这些类是动态生成的,所以我无法使用 .post-4836
和 .post-4837
进行选择。我想像 .post-*
这样选择。
最佳答案
您可以使用 $("[class*='post-']")
选择它们。然后你必须遍历它们,从类中获取数字,并检查你是否已经在列表中。如果您已经拥有它,请将其隐藏。否则,将其添加到列表中。
var groups = [];
$("[class*='post-']").each(function() {
var c = this.className.substring(this.className.indexOf("post-") + 5);
if (groups.indexOf(c) > -1)
$(this).parent().hide();
else
groups.push(c);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="product">
<div class="some-other-class-names post-4837">..1..</div>
</li>
<li class="product">
<div class="some-other-class-names post-4837">..2..</div>
</li>
<li class="product">
<div class="some-other-class-names post-4836">..a..</div>
</li>
<li class="product">
<div class="some-other-class-names post-4836">..b..</div>
</li>
<li class="product">
<div class="some-other-class-names post-4836">..c..</div>
</li>
注意:这假定 post-*
类始终是 class
属性中的最后一个。如果不能保证,您将不得不更改行:
var c = this.className.substring(this.className.indexOf("post-") + 5);
类似于:
var c = this.className.match(/post-\d+/)[0];
c = c.substring(c.indexOf("post-") + 5);
关于javascript - 只显示一个类的第一次出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49915816/