【问题标题】:select the second instance of a class and display none选择一个类的第二个实例并显示无
【发布时间】:2017-05-23 15:03:53
【问题描述】:

我的论坛上有太多的注销链接。我不想显示第二个和第三个,我只想显示第一个。

class = bbpresslogouturl

我试过了:

.bbpressloginurl:nth-last-of-type(2){display:none;}
.bbpressloginurl:nth-last-of-type(1){display:none;}

但这在使用 css 时不起作用。有没有办法使用 jQuery 选择第 n 个类?

【问题讨论】:

  • $('.bbpresslogouturl').not(':first').hide()
  • :nth-last-of-type关心元素类型。 CSS 中没有:nth-of-class。您将不得不求助于 Javascript。
  • 使用 :nth-child() or .eq() 而不是 .eq() 索引从 0 开始
  • 如前所述...使用nth-child w3schools.com/cssref/sel_nth-child.asp
  • 根据您的 HTML 结构,可能会有基于 CSS 的解决方案。如果我们不知道 HTML,就不可能说出来。

标签: jquery css class


【解决方案1】:

如果他们不是“兄弟/兄弟姐妹”

$('.bbpressloginurl').eq(1).hide();

如果是,你可以使用 css: 这将隐藏下一个兄弟

.bbpressloginurl:first-child + .bbpressloginurl{ display: none; }

这将隐藏所有下一个兄弟姐妹。

.bbpressloginurl:first-child ~ .bbpressloginurl{ display: none; }

甚至这个:

.bbpressloginurl:not(:first-child) { display: none; }

这取决于你没有共享的标记......以及你现有的 css 选择器

__

另外,
first-of-typelast-of-type 不能用于类名,只能用于元素(ul、h2、..)

【讨论】:

  • 这个词是siblings,不是兄弟。此外,即使他们是兄弟姐妹,也不意味着他们中的第一个是其父母的第一个孩子。即使是这样,您也必须使用兄弟选择器 ~ 而不是相邻选择器 +
  • 如果他们的 HTML 结构能够满足您的要求,这将是 OP 想要的,而这几乎不会。 我的论坛上有太多的注销链接。我不想显示第二个和第三个,只显示第一个。
  • 不是真的,如果您查看问题的标题...“选择类的第二个实例并显示无”;无论如何,我为许多情况提供了多种解决方案..
  • .bbpressloginurl ~ .bbpressloginurl { display: none; } 是唯一一个对我有用的人!
  • @BradTheBluefish,这取决于您的标记和现有的 CSS 选择器
【解决方案2】:

你可以使用:

<div class="test">
  1
</div>
<div class="test">
  2
</div>
<div class="test">
  3
</div>

和css:

.test {
  display: none;
}

.test:nth-child(1) {
  display: block !important;
}

查看fiddle

【讨论】:

    【解决方案3】:

    隐藏除第一个以外的所有内容

    $('.bbpresslogouturl').not(':first').hide();
    

    【讨论】:

      猜你喜欢
      • 2016-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-17
      • 2015-12-01
      • 2013-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多