javascript - 只显示一个类的第一次出现

标签 javascript jquery html css dom

我有以下 HTML 结构,这里类 post-4837post-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/

相关文章:

jquery - 如何更改 jQuery vmap 中的工具提示样式?

javascript - 努力使用 .querySelector 查询具有相同类名的特定元素

javascript - 随着时间的推移加速

javascript - 如何使用javascript清除 Canvas 层并将其另存为图像

javascript - jQuery 切换功能使文本变形

javascript - 初始化谷歌地图在模式框中不起作用

javascript - 使用 Javascript 将属性添加到 html 标签

html - 在thymeleaf spring框架中从本地目录插入图像(使用maven)

javascript - 在 Javascript 字符串中奇怪地使用反斜杠

javascript - $.get jquery 函数返回完整的 html 页面而不是数据中的 json