【问题标题】:Why is my nth-of-type selector not working? [duplicate]为什么我的第 n 个类型选择器不起作用? [复制]
【发布时间】:2019-01-17 06:52:32
【问题描述】:

https://codepen.io/Yarwaa/pen/jpXqjL

我有以下代码:

$(document).ready(function(){
  $('#button').click(function(){
    $('.row').append('<div class="col-4"><div class="text-container"><h1 class="heading">Something</h1></div></div>');
  });
});
.text-container:nth-of-type(odd){
   background-color: green;
   color: yellow;
}
.text-container:nth-of-type(even){
  background-color: yellow;
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Click</button>
<div class="container">
  <div class="row"></div>
</div>

我想做什么:

当我点击按钮时,我需要获得text-containerbackground-color: green 用于奇数,以及带有background-color: yellow 的容器。

问题是:每个容器都被认为是一个奇数,如果我在col-4 容器中添加另一个类并为这个类设置背景颜色,那么它将删除列中的所有填充,它们会非常彼此靠近。

【问题讨论】:

    标签: jquery css css-selectors


    【解决方案1】:

    您误解了:nth-of-type() 的工作原理。

    您添加的每个.text-container 都是odd

    :nth-of-type() 计数指的是 在任何给定上下文中的第 n 个类型,在您的情况下是 &lt;div class="col-4"&gt;。其中,您的每个&lt;div class="text-container"&gt; 都是:first-of-type

    这就是你可能需要的(我改变的只是 CSS 选择器):

    $(document).ready(function() {
      $('#button').click(function() {
        $('.row').append('<div class="col-4"><div class="text-container"><h1 class="heading">Something</h1></div></div>');
      });
    });
    .row>div:nth-of-type(odd) .text-container {
      background-color: green;
      color: yellow;
    }
    
    .row>div:nth-of-type(even) .text-container {
      background-color: yellow;
      color: green;
    }
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.2/css/bootstrap.min.css" rel="stylesheet"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button id="button">Click to add a div</button>
    <div class="container">
      <div class="row"></div>
    </div>

    【讨论】:

      【解决方案2】:

      由于您的文本容器位于它们自己的 div 中,因此它们始终是第一个类型。改用你的 JS 试试这个:

      $(document).ready(function(){
        $('#button').click(function(){
          $('.row').append('<div class="col-4 text-container"><h1 class="heading">Something</h1></div>');
        });
      });
      

      那么你所有的文本容器都是兄弟姐妹,它可以工作!

      【讨论】:

        猜你喜欢
        • 2014-09-25
        • 1970-01-01
        • 2021-01-08
        • 2016-11-20
        • 2012-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-02
        相关资源
        最近更新 更多